LeetCode-67 Add Binary(二进制数相加)
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
public class Solution {
public String addBinary(String a, String b) {
int sflag = 0;
String c = "";
String lener = a.length()>b.length()?a:b;
int temp = Math.min(a.length(), b.length());
int i = 1;
while(i <= Math.min(a.length(),b.length())){
c = (a.charAt(a.length()-i) + b.charAt(b.length()-i)+ sflag)%2 + c;
if (a.charAt(a.length()-i)-48 + b.charAt(b.length()-i) - 48 + sflag > 1) {
sflag = 1;
}else {
sflag = 0;
}
i++;
}
if (sflag == 0) {//如果进位为0,多出的位直接添加在c的前面即可
return lener.substring(0,lener.length()-temp) + c;
} else {//进位不为0,则继续新位上的值+进位,继续判断。
for (int j = lener.length() - temp - 1; j >= 0; j--) {
System.out.println(c);
if (sflag > 0) {
c = (lener.charAt(j) -48 + sflag)%2 + c;
sflag = lener.charAt(j) - 48 + sflag > 1?1:0;
} else {//一旦进位为0,就直接截取剩下的位添加到c的前面即可。
return lener.subSequence(0, j+1)+c;
}
}
}
if (sflag == 1) {//如果加到最后扔有进位,则需要补一位1。
c = 1 + c;
}
return c;
}
}
然后又到网上看了看别人简练直观的代码,值得学习:
public class Solution {
public String addBinary(String a, String b) {
int flag = 0;
int aIndex = a.length() - 1;
int bIndex = b.length() - 1;
String c = "";
while(aIndex >= 0 && bIndex >= 0)
{
int num = a.charAt(aIndex) - '0' + (b.charAt(bIndex) - '0') + flag;
flag = num / 2;
num %= 2;
c = (char)(num + '0') + c;
aIndex--;
bIndex--;
}
while(aIndex >= 0)
{
int num = a.charAt(aIndex) - '0' + flag;
flag = num / 2;
num %= 2;
c = (char)(num + '0') + c;
aIndex--;
}
while(bIndex >= 0)
{
int num = b.charAt(bIndex) - '0' + flag;
flag = num / 2;
num %= 2;
c = (char)(num + '0') + c;
bIndex--;
}
if (flag > 0)
c = (char)(flag + '0') + c;
return c;
}
}