将一个由一和零组成的数组转换为相应的二进制值,然后转换为整数。PHP

huangapple go评论97阅读模式
英文:

Given an array of ones and zeroes, convert the equivalent binary value to an integer.PHP

问题

以下是翻译好的内容:

我尝试了以下解决方案,但不明白为什么结果不正确,希望能得到帮助。非常感谢。

  1. function binaryArrayToNumber($arr) {
  2. $sumarr = [];
  3. for ($i = count($arr); $i > 0; $i--) {
  4. $power = pow(2, ($i - 1));
  5. $sumarr[] = $power * $arr[$i - 1];
  6. }
  7. return array_sum($sumarr);
  8. }

示例答案将是
测试: [1, 1, 1, 1] ==> 15
测试: [1, 0, 1, 1] ==> 11

英文:

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.

  1. function binaryArrayToNumber($arr) {
  2. $sumarr = [];
  3. for($i=count($arr);$i>0 ;$i--){
  4. $power= pow(2,($i-1));
  5. $sumarr[]=$power*$arr[$i-1];
  6. }
  7. return array_sum($sumarr);
  8. }

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

答案1

得分: 2

你的代码中存在逻辑错误。你的pow计算是错误的,因为你使用了$i来计算幂次。

尝试以下代码,它将输出你期望的结果:

  1. function binaryArrayToNumber($arr) {
  2. $num = 0;
  3. $pow = 0;
  4. for($i = count($arr) - 1; $i >= 0; $i--) {
  5. $num += pow(2, ($pow++)) * $arr[$i];
  6. }
  7. return $num;
  8. }
  9. echo binaryArrayToNumber([1, 1, 1, 1]);
  10. echo binaryArrayToNumber([1, 0, 1, 1]);

输出:

  1. 15
  2. 11
英文:

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:

  1. function binaryArrayToNumber($arr) {
  2. $num = 0;
  3. $pow = 0;
  4. for($i = count($arr) - 1; $i >= 0; $i--) {
  5. $num += pow(2, ($pow++)) * $arr[$i];
  6. }
  7. return $num;
  8. }
  9. echo binaryArrayToNumber([1, 1, 1, 1]);
  10. echo binaryArrayToNumber([1, 0, 1, 1]);

Output:

  1. 15
  2. 11

huangapple
  • 本文由 发表于 2020年1月3日 18:52:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577268.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定