LeetCode刷题笔录Add Binary
来源:程序员人生 发布时间:2014-10-13 00:44:47 阅读次数:2436次
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
具体一位一位地加就行了,考虑进位的问题。还有最后记得把生成的string反过来再返回,因为我们是从最低位开始加的。
public class Solution {
public String addBinary(String a, String b) {
if(a == null || a.length() == 0)
return b;
if(b == null || b.length() == 0)
return a;
StringBuilder res = new StringBuilder();
int i = a.length() - 1;
int j = b.length() - 1;
int digit;
int carry = 0;
while(i >= 0 && j >= 0){
digit = (int)(a.charAt(i) - '0' + b.charAt(j) - '0' + carry);
carry = digit / 2;
digit %= 2;
res.append(digit);
i--;
j--;
}
while(i >= 0){
digit = (int)(a.charAt(i) - '0' + carry);
carry = digit / 2;
digit %= 2;
res.append(digit);
i--;
}
while(j >= 0){
digit = (int)(b.charAt(j) - '0' + carry);
carry = digit / 2;
digit %= 2;
res.append(digit);
j--;
}
//don't forget to add the final carry(if exists)
if(carry > 0){
res.append(carry);
}
return res.reverse().toString();
}
}
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠