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(); } }
原文:http://blog.csdn.net/likecool21/article/details/38935287