1. 题⽬链接:67.⼆进制求和
2. 题⽬描述:
3. 解法(模拟⼗进制的⼤数相加的过程):
算法思路:
模拟⼗进制中我们列竖式计算两个数之和的过程。但是这⾥是⼆进制的求和,我们不是逢⼗进⼀,⽽ 是逢⼆进⼀。
C++算法代码:
class Solution
{
public:
string addBinary(string a, string b)
{
string answer; // 答案
//翻转两个字符串
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
int cur1=0,cur2=0;
int t=0; //进位
while(cur1<a.size()||cur2<b.size()||t)
{
if(cur1<a.size())
{
t+=a[cur1++]-'0';
}
if(cur2<b.size())
{
t+=b[cur2++]-'0';
}
answer+=to_string(t%2);
t/=2;
}
//翻转答案
reverse(answer.begin(),answer.end());
return answer;
}
};
Java算法代码:
class Solution
{
public String addBinary(String a, String b)
{
StringBuffer ret = new StringBuffer();
int cur1 = a.length() - 1, cur2 = b.length() - 1, t = 0;
while (cur1 >= 0 || cur2 >= 0 || t != 0)
{
if (cur1 >= 0) t += a.charAt(cur1--) - '0';
if (cur2 >= 0) t += b.charAt(cur2--) - '0';
ret.append((char)('0' + (char)(t % 2)));
t /= 2;
}
ret.reverse();
return ret.toString();
}
}