您的位置 首页 php

【PHP学习】实现两个n位二进制整数相加

本篇文章讲述的是用PHP实现两个n位二进制整数相加 ,具有参考价值,感兴趣的朋友可以学习了解一下。

问题:两个n位二进制数分别存储在两个n元数组A和B中,这两个整数的和存在一个n+1元的数组C中
答:此问题主要是考察相加进位的问题,元素1+1 =0 并且往前进一位
ADD-BINARY(A,B)
  C=new integer[A.length+1]
  carry=0
  for i=A.length downto 1
    C[i+1]=(A[i]+B[i]+carry)%2
    carry=(A[i]+B[i]+carry)/2
  C[i]=carry

代码如下:

<?phpfunction addBinary($A,$B){        $C=array();        $length=count($A);        $carry=0;        for($i=$length-1;$i>=0;$i--){                //当前位的数字逻辑 1+1=0 1+0=1                $C[$i+1]=($A[$i]+$B[$i]+$carry)%2;                //进位的数字逻辑  1+1=1 1+0=0                $carry=intval(($A[$i]+$B[$i]+$carry)/2);        }           $C[$i+1]=$carry;        return $C; }$A=array(0,1,1,0);$B=array(1,1,1,1);$C=addBinary($A,$B);var_dump($C);

相关教程:PHP视频教程

以上就是【PHP学习】实现两个n位二进制整数相加的详细内容,更多请关注求知技术网其它相关文章!

文章来源:智云一二三科技

文章标题:【PHP学习】实现两个n位二进制整数相加

文章地址:https://www.zhihuclub.com/5149.shtml

关于作者: 智云科技

热门文章

评论已关闭

1条评论

  1. Hello there! I know this is kind of off topic but I was wondering which blog platform
    are you using for this site? I’m getting fed up of WordPress
    because I’ve had issues with hackers and I’m looking at alternatives for another platform.
    I would be fantastic if you could point me in the
    direction of a good platform.

网站地图