Add Binary
题目
Given two binary strings, return their sum (also a binary string).
For example,
a ="11"
b ="1"
Return"100"
.
分析
- convert String to char array for a, b
- initializ m , n to be the length of a, b
- new a StringBuilder, in order to append and insert String easily
- while loop to traverse every digit of a, b from rightmost to leftmost, including considering about a carry
- pay attention to converting binary to decimal, using Character.forDigit
图解
解法
class Solution {
public String addBinary(String a, String b) {
char[]arrayA = a.toCharArray();
char[] arrayB = b.toCharArray();
int m = a.length()-1;
int n = b.length()-1;
int carry= 0;
StringBuilder sb = new StringBuilder();
while(m>=0 || n>=0 || carry>0){
int updateA = m>=0 ? arrayA[m--]-'0' : 0;
int updateB = n>=0 ? arrayB[n--]-'0' : 0;
int sum = updateA + updateB + carry;
sb.insert(0,Character.forDigit(sum%2, 10)); // 用Character.forDigit 因为此题涉及到二进制转十进制
carry = sum /2;
}
return sb.toString();
}
}