题目要求:给出两个二进制的字符串数组,求相加之后的值。
tags:math,string
思路:
1.从后向前计算,逐个计算相加之后的值,
2.由于两个字符串可能不一样长,可以设计两个指针,一个指向字符串1,另一个指向字符串2,先判断是否数组越界,再根据情况赋值(可用三元运算符)。
//从后往前,逐个计算相加之后的值
public String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length()-1;
int j = b.length()-1;
int c = 0;
while(i>-1||j>-1||c==1){
int aByte = (i>-1)?Character.getNumericValue(a.charAt(i--)):0;
int bByte = (j>-1)?Character.getNumericValue(b.charAt(j--)):0;
int result = ((aByte+bByte+c)==3||(aByte+bByte+c)==1)?1:0;
c = (aByte+bByte+c)>=2 ? 1:0;
sb.append(result);
}
return sb.reverse().toString();
}