两个二进制相加

伪代码:

for i=n-1 downto 0

  if A[i]+B[i]==0 //情况1

    if flag==0

      C[i+1]=0

    else

       C[i+1]=1

    flag=0

  elseif A[i]+B[i]==1  //情况2

    if flag==0

      C[i+1]=1

    else

       C[i+1]=0

       flag==1

  else                  //情况3

    if flag==0

      C[i+1]=0

    else

       C[i+1]=1

     flag==1C[0]=flag
时间: 2024-10-04 12:53:12

两个二进制相加的相关文章

LeetCode 67. Add Binary (二进制相加)

Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 题目标签:Math 题目给了我们两个string a 和 b,让我们把这两个二进制 相加. 首先把两个string 的长度得到,然后从右向左 取 两个string 的 digit. 增设一个 carry = 0: 每一轮把 digit

LeetCode Add Binary 两个二进制数相加

1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 if(a==""&&b=="") return ""; 5 if(a=="") return b; 6 if(b=="") return a; 7 char *pa=&a[0],*pb=&b[0]; 8 int na=0,nb=0;

LeetCode OJ:Add Binary(二进制相加)

Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 简单的二进制相加而已,只不过传入的参数是字符串而已.为了方便,先将string  reverse了一下,代码如下: 1 class Solution { 2 public: 3 string addBinary(string a, s

两个大数相加 ----Javascrit 实现

(function(){ var addLarge = function(n1,n2){ var over = 0; var ret = ""; var len = Math.min(n1.length,n2.length); var sln1 = n1.substr(n1.length - len,n1.length ); var sln2 = n2.substr(n2.length - len,n2.length ); for(var i = len;i > 0; i--)

两个有理数相加(要求输入时以分数形式,输出时也以分数形式)

上大一,老师布置了一道题,内容就是:两个有理数相加(要求输入时以分数形式,输出时也以分数形式),这道题用了大概2个多小时吧(欢迎指导),废话不多说了,直接上程序: #include<iostream>using namespace std; class rational{public: void setnumber(int n,int d); void getnumber(int& n,int& d); void gcd(int n,int d); bool operator=

LeetCode 67 Add Binary(二进制相加)(*)

翻译 给定两个二进制字符串,返回它们的和(也是二进制字符串). 比如, a = "11" b = "1" 返回 "100". 原文 Given two binary strings, return their sum (also a binary string). For example, a = "11" b = "1" Return "100". 分析 我一開始写了这个算法,尽管实现

两个链表相加

1 题目 You are giventwo linked lists representing two non-negative numbers. The digits are storedin reverse order and each of their nodes contain a single digit. Add the twonumbers and return it as a linked list. Input: (2 -> 4 -> 3)+ (5 -> 6 ->

iOS中计算两个大数相加算法(OC实现)

我们知道计算机的数据类型不同,所能表示的数据量级也不相同,比如: unsigned int : 0-4294967295   int : -2147483648-2147483647 unsigned long : 0-4294967295long :  -2147483648-2147483647long long : -9223372036854775808 ~ 9223372036854775807unsigned long long : 0 ~ 18446744073709551615

[CareerCup] 2.5 Add Two Numbers 两个数字相加

2..5 You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1's digit is at the head of the list. Write a function that adds the two numbers and returns the su