This article talks about using PHP to add two n-bit binary integers. It has reference value. Interested friends can learn about it.
Question: Two n-bit binary numbers are stored in two n-element arrays A and B respectively. The sum of these two integers is stored in an n-element array C.
Answer: This question is mainly It is a problem of examining the carry of addition. Element 1 1 =0 and advances one bit
ADD-BINARY(A,B)
C=new integer[A.length 1]
carry=0
for i=A.length downto 1
## C[i]=carry
The code is as follows:
<?php function 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);
Related tutorials:
PHP video tutorialThe above is the detailed content of [PHP Learning] Implement the addition of two n-bit binary integers. For more information, please follow other related articles on the PHP Chinese website!