0

我知道这是可能的,但它正在让我陷入困境。

想象一下有一组代码及其描述。

array(
0 => "Success",
1 => "File Not Found",
2 => "Could not create file",
4 => "Directory not found",
8 => "Directory could not be created",
16 => "Disk damaged"
)

(不要介意示例中的错误代码,我只是编造的。)

收到错误代码 1 时很容易解决。现在想象得到一个错误代码“7”,我需要它返回该错误代码中的所有选项。所以 7 由“4 + 2 + 1”组成。

希望我的问题很清楚。这几乎就像在 php.ini 中放置一个错误代码级别。它将错误累积在一起的地方。

4

2 回答 2

2

有许多不同的方法可以做到这一点。这是一个将数字转换为二进制并迭代数字的方法:

function number_to_sum_of_powers($number) {
    $binary = strrev(decbin($number));
    $power = 1;
    $summands = array();
    foreach(str_split($binary) as $digit) {
        if($digit === '1') {
            $summands[] = $power;
        }
        $power *= 2;
    }
    return $summands;
}

这是用 调用它时的结果7

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(4)
}
于 2012-11-30T09:09:41.297 回答
0

如果你想通过 2 的幂来做到这一点,即基本的数学方式,在 php

   <?php 
        $array = array(
        0 => "Success",
        1 => "File Not Found",
        2 => "Could not create file",
        4 => "Directory not found",
        8 => "Directory could not be created",
        16 => "Disk damaged"
        );

        $total_code = 7; 
        $error_code = 1; 

        while($total_code >= 1){
             if($total_code % 2 == 1){
                  echo $array[$error_code]."<br>";
              }
              $total_code /= 2;
              $error_code *= 2;
       }
   ?>

在 Java 中

    HashMap<Integer,String> errors = new HashMap<Integer, String>();

    errors.put(0, "Success");
    errors.put(1, "File Not Found");
    errors.put(2, "Could not create file");
    errors.put(4, "Directory not found");
    errors.put(8, "Directory could not be created");
    errors.put(16, "Disk damaged");

    int total_code = 7;
    int error_code = 1;

    while(total_code >= 1) {
        if(total_code % 2 == 1)
            System.out.println(errors.get(error_code));
        total_code /= 2;
        error_code *= 2;
    }
于 2012-11-30T09:21:25.563 回答