轉載請註明作者和出處: http://blog.csdn.net/c406495762
Given two binary strings, return their sum (also a binary string).
For example,
a = “11”
b = “1”
Return “100”
題目:兩個代表二進制數字的字符串相加
思路:從低位開始相加,逢二進一:
class Solution {
public:
string addBinary(string a, string b) {
string s = "";
//i字符串a的索引值,j字符串b的索引值
int c = 0, i = a.size() - 1, j = b.size() - 1;
//字符串a和b沒有遍歷完,或者存在進位,繼續計算
while(i >= 0 || j >= 0 || c == 1)
{
//三目運算符:低位相加
c += i >= 0 ? a[i--] - '0' : 0;
c += j >= 0 ? b[j--] - '0' : 0;
//結果
s = char(c % 2 + '0') + s;
//進位計算
c /= 2;
}
//返回結果
return s;
}
};
Language:Python
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if len(a)==0: return b
if len(b)==0: return a
if a[-1] == '1' and b[-1] == '1':
return self.addBinary(self.addBinary(a[0:-1],b[0:-1]),'1') +'0'
if a[-1] == '0' and b[-1] == '0':
return self.addBinary(a[0:-1],b[0:-1])+'0'
else:
return self.addBinary(a[0:-1],b[0:-1])+'1'
LeetCode題目彙總: https://github.com/Jack-Cherish/LeetCode