解题思路:
- 首先把字符串a和b补齐到同样长度,前面补零
- 然后对应位做加法器,设置一个进位位
- 字符转换成数字需要 -'0'
- 数字转换为字符需要 +'0'
- 结果字符数组需要比a和b多一位
- 最前面的一位为最后的进位位
- 判断最后的进位如果为1,则设置结果数组第一位为1,创建字符串用result数组全部
- 如果为0,则设置结果字符数组第一位为0,创建字符串用1到最后
- 注意
- 1和0都需要转换为char,不然会乱码,因为是acssi码
- 创建字符1到最后,是1到result.lenght-1
代码:
package leetcode;
/**
* Given two binary strings, return their sum (also a binary string). For
* example, a = "11" b = "1" Return "100".
*
*/
public class AddBinary {
public static void main(String[] args) {
String a = "101";
String b = "1";
int max_a_b = Math.max(a.length(), b.length());
if (a.length() >= b.length()) {
b = String.format("%0" + max_a_b + "d", Integer.parseInt(b));
} else {
a = String.format("%0" + max_a_b + "d", Integer.parseInt(a));
}
System.out.println("after zeroize string a is " + a + " "
+ "after zeroize string b is " + b);
char[] achar = a.toCharArray();
char[] bchar = b.toCharArray();
char[] result = new char[Math.max(achar.length, bchar.length) + 1];
int k = result.length - 1;// k is to the start of result
int i = max_a_b - 1;
int carry = 0;// 进位
int aint = 0;
int bint = 0;
while (i >= 0) {
aint = achar[i] - '0';
bint = bchar[i] - '0';
if (aint + bint + carry > 1) {
result[k] = (char) ('0' + aint + bint + carry - 2);
carry = 1;
} else {
result[k] = (char) ('0' + aint + bint + carry);
carry = 0;
}
k--;
i--;
}
if (carry == 1) {
result[k] = (char) ((char) carry + '0');
System.out.println("result is " + new String(result));
} else {
result[k] = (char) ((char) carry + '0');
System.out.println("result is "
+ new String(result, 1, result.length - 1));
}
}
}