Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
题目含义:将两个字符串进行二进制加减法。
思路:从最后一位开始依次计算,注意进位
1 public String addBinary(String a, String b) { 2 StringBuilder sb = new StringBuilder(); 3 int i=a.length()-1,j = b.length() -1; 4 int carry = 0; 5 while (i>=0 | j>=0) 6 { 7 int sum = carry; 8 if (i>=0) sum += a.charAt(i--) - '0'; 9 if (j>=0) sum += b.charAt(j--) - '0'; 10 sb.append(sum%2); 11 carry = sum/2; 12 } 13 if (carry != 0 ) sb.append(carry); 14 return sb.reverse().toString(); 15 }