Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题意:给定2个字符串,代表2个二进制数,求这2个数相加得到的字符串。
直接看代码:
public class Solution {
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length()-1;
int j = b.length()-1;
int c = 0;
while(i>=0||j>=0){
int sum = c;
if(i>=0) sum += a.charAt(i--)-'0';
if(j>=0) sum += b.charAt(j--)-'0';
sb.append(sum%2);
c = sum/2;
}
if (c != 0) sb.append(c);
return sb.reverse().toString();
}
}