题目:
有两个字符串里面仅包含二进制,然后让两个字符串内的二进制数字从右往左相加进位得到结果.
例如:a=”11”,b=”1” 结果是c=”100”,a中最右侧的1与b中的1相加得2,2的二进制是10,在此位保留一个0,1作为进位, 在a中右侧的倒数第二个1与进位1相加得2,2的二进制是10,此位保留一个0,由于左侧没有数字的,把进位追加到左侧.
例如 a=”11”,b=”11” 结果是c=”110”
例如 a=”111”,b=”111” 结果是c=”1100”
例如 a=”1111”,b=”1111” 结果是c=”11110”
例如 a=”1010”,b=”11” 结果是c=”1101”
另一个角度,”11”的十进制是3,”1”的十进制是1,两个相加的十进制是4,那么二进制则是”100”
求a,b串内二进制相加的结果
思路:
在进位相加的过程中发现,相加值只可能为0,1,2,3,由此就可以解题
未简化版本
private static String getCarryResult2(String a, String b) {
StringBuilder sb = new StringBuilder();
int aIndex = a.length() - 1;
int bIndex = b.length() - 1;
int carry = 0;
while (!(aIndex == -1 && bIndex == -1)) {
int aResult = 0;
if (aIndex >= 0) {
aResult = a.charAt(aIndex--) - '0';
}
int bResult = 0;
if (bIndex >= 0) {
bResult = b.charAt(bIndex--) - '0';
}
int result = aResult + bResult + carry;
if (result == 3) {
carry = 1;
sb.append('1');
} else if (result == 2) {
carry = 1;
sb.append('0');
} else if (result == 1) {
carry = 0;
sb.append('1');
} else {
sb.append('0');
}
}
if (carry == 1) {
sb.append('1');
}
return sb.reverse().toString();
}
简化版本
public static void main(String[] args) {
String a = "1111";
String b = "1111";
String result = getCarryResult(a, b);
System.out.println(result);
}
private static String getCarryResult(String a, String b) {
StringBuilder sb = new StringBuilder();
int aIndex = a.length() - 1;
int bIndex = b.length() - 1;
int carry = 0;
while (!(aIndex == -1 && bIndex == -1)) {
int aResult = aIndex >= 0 ? (a.charAt(aIndex--) - '0') : 0;
int bResult = bIndex >= 0 ? (b.charAt(bIndex--) - '0') : 0;
int result = aResult + bResult + carry;
carry = result >= 2 ? 1 : 0;
sb.append((result & 0x1) == 1 ? 1 : 0);
}
sb.append(carry == 0 ? "" : carry);
return sb.reverse().toString();
}
`