您的位置:首页 > 其它

leetcode 67. Add Binary

2016-04-15 21:08 323 查看

题意

两个字符串存放一个整数的二进制位,返回相加后的数的字符串表示

题解

如题

代码

class Solution {
public:
string addBinary(string a, string b) {
string result;
//int minsize = min(a.length(), b.length());
int carry = 0;
int i = a.length() - 1, j = b.length() - 1;

for(; i >= 0 && j >= 0; i--, j--)
{
int num = a[i] - '0' + b[j] - '0' + carry;
carry = num / 2;
result += (num % 2 + '0');
}
while(i >= 0)
{
int num = a[i] - '0' + carry;
carry = num / 2;
result += (num % 2 + '0');
i--;
}
while(j >= 0)
{
int num = b[j] - '0' + carry;
carry = num / 2;
result += (num % 2 + '0');
j--;
}
if(carry)
result += '1';
reverse(result.begin(), result.end());
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: