标签:
给定两个二进制字符串,返回他们的和(用二进制表示)。
思路
string s = ""; 目标字符串
cp 存储进位;取 0或1
sum = a[i] + b[i] + cp;分为四种情况
0 s += ‘0‘; cp = 0;
1 s += ‘1‘; cp = 0;
2 s += ‘0‘; cp = 1;
3 s += ‘1‘; cp = 1;
C++实现
string addBinary(string& a, string& b) { // Write your code here int i = a.size() - 1; int j = b.size() - 1; int cp = 0; string s = ""; while (i >= 0 || j >= 0) { char a1; char b1; if (i >= 0) a1 = a[i]; else a1 = ‘0‘; if (j >= 0) b1 = b[j]; else b1 = ‘0‘; int p = (a1 - ‘0‘) + (b1 - ‘0‘) + cp; if (p == 0) { s = ‘0‘ + s; cp = 0; } else if (p == 1) { s = ‘1‘ + s; cp = 0; } else if (p == 2) { s = ‘0‘ + s; cp = 1; } else if (p == 3) { s = ‘1‘ + s; cp = 1; } if(i != -1) i--; if(j != -1) j--; } if (cp == 1) { s = ‘1‘ + s; } return s; }
标签:
原文地址:http://www.cnblogs.com/Smallhui/p/5448343.html