[LeetCode]Add Binary

給定字符串a,b,分別表示兩個二進制數。將a,b的二進制和以字符串形式返回。spa

Given two binary strings, return their sum (also a binary string).code

For example,
a = "11"
b = "1"
Return "100".blog

思路:模擬二進制加法過程,從最低位開始rem

難點在於進位的計算。記進位符爲carry, 該位的和爲num字符串

int num = a[i]-'0'+b[j]-'0'+carry;
carry = num/2;
num %= 2;

代碼string

 1 class Solution {
 2 public:
 3     string addBinary(string a, string b) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         string ret;
 7         int i=a.length()-1, j=b.length()-1;
 8         int carry = 0;
 9         while(i>=0 && j>=0)
10         {
11             int num = a[i]-'0'+b[j]-'0'+carry;
12             carry = num/2;
13             num %= 2;
14             ret = char(num+'0') + ret;
15             --i; --j;
16         }
17         // add carry and remaining string
18         while(i>=0)
19         {
20             int num = a[i]-'0'+carry;
21             carry = num/2;
22             num %=2;
23             ret = char(num+'0')+ret;
24             --i;
25         }
26         while(j>=0)
27         {
28             int num = b[j]-'0'+carry;
29             carry = num/2;
30             num %=2;
31             ret = char(num+'0')+ret;
32             --j;
33         }
34         
35         if(carry>0)
36             ret = "1"+ret;
37         
38         return ret;
39     }
40 };
相關文章
相關標籤/搜索