标签:
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, string b) { 4 reverse(a.begin(), a.end()); 5 reverse(b.begin(), b.end()); 6 int len1 = a.length(); 7 int len2 = b.length(); 8 string result; 9 int flag ,val; 10 flag = val = 0; 11 int i; 12 for(i = 0; i < len1 && i < len2; ++i){ 13 val = (a[i] - ‘0‘) + (b[i] - ‘0‘) + flag; 14 result.append(1, val % 2 + ‘0‘); 15 flag = val/2; 16 } 17 while (i < len1) { 18 val = a[i] - ‘0‘+ flag; 19 result.append(1, val % 2 + ‘0‘); 20 flag = val/2; 21 ++i; 22 } 23 while (i < len2 ){ 24 val = b[i] - ‘0‘+ flag; 25 result.append(1, val % 2 + ‘0‘); 26 flag = val/2; 27 ++i; 28 } 29 cout << "flag " << flag << endl; 30 if(flag != 0) 31 result.append(1, ‘1‘); 32 reverse(result.begin(), result.end()); 33 return result; 34 } 35 };
标签:
原文地址:http://www.cnblogs.com/-wang-cheng/p/4870243.html