Given two binary strings, return their sum (also a binary string).
Example
a = 11
b = 1
Return 100
二进制加法,解题思路就是从尾到头遍历,一个个数提出来相加,还需要一个adder来存储当前是否加一的状态。如果a或b字符串还没有遍历完,继续执行上面的步骤,最后还需要检测一下adder是否为1。
public class Solution {
/**
* @param a a number
* @param b a number
* @return the result
*/
public String addBinary(String a, String b) {
// Write your code here
if(a == null || b == null){
return a+b;
}
int m = a.length()-1;
int n = b.length()-1;
int adder = 0;
String rst = "";
while( m >= 0 && n >= 0) {
int sum = (int)(a.charAt(m) - '0') + (int)(b.charAt(n) - '0') + adder;
rst = String.valueOf(sum % 2) + rst;
adder = sum/2;
m--;
n--;
}
while(m >= 0) {
int sum = (int)(a.charAt(m) - '0') + adder;
rst = String.valueOf(sum % 2) + rst;
adder = sum/2;
m--;
}
while(n >= 0) {
int sum = (int)(b.charAt(n) - '0') + adder;
rst = String.valueOf(sum % 2) + rst;
adder = sum/2;
n--;
}
if(adder == 1) {
rst = "1" + rst;
}
return rst;
}
}