Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1
or 0
.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
注意:
StringBuilder.insert(int offset, char c) 表示将char放入offset这个偏移量
Character.forDigit(int digit, int radix) 返回radix进制下,该digit所代表的char
代码
1 class Solution { 2 public String addBinary(String a, String b) { 3 StringBuilder sb = new StringBuilder(); // new a StringBuilder because it will be easy to append 4 5 char[] arrayA = a.toCharArray();// convert char to array 6 char[] arrayB = b.toCharArray();// convert char to array 7 8 int i = a.length()-1; 9 int j = b.length()-1; 10 int carry = 0; 11 12 while(i>=0 || j>=0 || carry >0){ 13 int updateA = i>=0 ? arrayA[i--]-'0':0; 14 int updateB = j>=0 ? arrayB[j--]-'0':0; 15 int sum = updateA + updateB + carry; 16 sb.insert(0, Character.forDigit(sum%2, 10)); // I convert this sum to binary then insert to sb 17 carry = sum/2; // coz it is binary, carry would be sum/2 18 } 19 return sb.toString(); // convert StringBuilder to String 20 } 21 }