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(); } }