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 にエラーコードレベルを入れるようなものです。エラーを一緒に蓄積する場所。

4

2 に答える 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 に答える