Given two binary strings, return their sum (also a binary string).
For example,a = "11"
b = "1"
Return "100"
给你两个二进制字符串,将两者相加,返回一个新的二进制字符串。
例如:
a="11";
b="1";
返回"100";
三、题目分析
本题看起来是一个字符串相加处理,其实是为大整数相加提供了一个思路;算法的关键点是处理好进位,从后往前一步一步相加即可。
public class Solution {
public String addBinary(String a, String b) {
int aLen = a.length();
int bLen = b.length();
String re = "";
int next = 0;
while(aLen>0||bLen>0||next>0){
int aInt = 0;
if(aLen>0){
aInt = a.charAt(aLen-1)-'0';
aLen--;
}
int bInt = 0;
if(bLen>0){
bInt = b.charAt(bLen-1)-'0';
bLen--;
}
re=new Integer((aInt+bInt+next)%2)+re;
next = (aInt+bInt+next)/2;
}
return re;
}
}
class Solution {
public:
string addBinary(string a, string b) {
char carryBit = '0';
int alen = a.size()-1;
int blen = b.size()-1;
string sumStr = "";
while(alen>=0||blen>=0){
char aChar = alen>=0?a[alen]:'0';
char bChar = blen>=0?b[blen]:'0';
int sum=(carryBit-'0')+(aChar-'0')+(bChar-'0');
carryBit = (char)('0'+sum/2);
sumStr=((char)('0'+sum%2))+sumStr;
alen--;
blen--;
}
sumStr=carryBit=='1'?(carryBit+sumStr):sumStr;
return sumStr;
}
};
米途小码
网友评论