[PHP Learning] Implement the addition of two n-bit binary integers

little bottle
Release: 2023-04-06 11:14:02
forward
1758 people have browsed it

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);
Copy after login

Related tutorials:

PHP video tutorial

The 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!

Related labels:
php
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!