0

I have tried the below solution but i dont see why i dont the get the results right , any help is appreciated. Thanks a lot.

function binaryArrayToNumber($arr) {

    $sumarr = []; 

    for($i=count($arr);$i>0 ;$i--){

        $power= pow(2,($i-1));
        $sumarr[]=$power*$arr[$i-1];    
    }

    return array_sum($sumarr); 

}

Example answer would be Testing: [1, 1, 1, 1] ==> 15 Testing: [1, 0, 1, 1] ==> 11

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Naveen DINUSHKA
  • 1,497
  • 3
  • 19
  • 37

1 Answers1

2

You've got a logical error in your code. Your pow calculation was incorrect as you were using $i to calculate the power.

Try the following which will output the result you expect:

function binaryArrayToNumber($arr) {
    $num = 0; 
    $pow = 0;

    for($i = count($arr) - 1; $i >= 0; $i--) {
        $num += pow(2, ($pow++)) * $arr[$i];
    }

    return $num;
}

echo binaryArrayToNumber([1, 1, 1, 1]);
echo binaryArrayToNumber([1, 0, 1, 1]);

Output:

15
11
Martin
  • 16,093
  • 1
  • 29
  • 48