一.题目
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
Show Tags
Have you met this question in a real interview?
Yes
No
二.解题技巧
这道题没有什么技巧,只是考虑到两个二进制数相加,得到的结果最多也就比最长的那个二进制数多一位,因此可以预先分配一个string,然后从最低位开始计算,在输出最终结果的时候,需要考虑最高位是否为0的情况。在逐位进行相加的时候,还需要考虑进位的情况。
三.实现代码
class Solution
{
public:
string addBinary(string a, string b)
{
int A_SIZE = a.size();
int B_SIZE = b.size();
int C_SIZE = (A_SIZE > B_SIZE? A_SIZE : B_SIZE) + 1;
string Result(C_SIZE, '0');
unsigned char TmpA = '0';
unsigned char TmpB = '0';
unsigned char C = '0';
unsigned char TmpBit = '0';
A_SIZE--;
B_SIZE--;
while (A_SIZE >= 0 || B_SIZE >= 0)
{
TmpA = '0';
TmpB = '0';
if (A_SIZE >= 0)
{
TmpA = a[A_SIZE--];
}
if (B_SIZE >= 0)
{
TmpB = b[B_SIZE--];
}
unsigned char Count = (TmpA - '0') + (TmpB - '0') + (C - '0');
TmpBit = Count % 2 + '0';
C = Count / 2 + '0';
Result[--C_SIZE] = TmpBit;
}
Result[--C_SIZE] = C;
if (Result[0] == '0')
{
return Result.substr(1);
}
return Result;
}
};
四.体会
这道题是一个细节题,没有过多的算法在里面。
版权所有,欢迎转载,转载请注明出处,谢谢
![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)