给定两个 01 字符串 a 和 b ,请计算它们的和,并以二进制字符串的形式输出。输入为 非空 字符串且只包含数字 1 和 0。
class Solution {
public String addBinary(String a, String b) {
//使用StringBuilder更方便:字符串倒置以及字符的添加
StringBuilder aSb = new StringBuilder(a);
StringBuilder bSb = new StringBuilder(b);
a = aSb.reverse().toString();
b = bSb.reverse().toString();
char aArray[] = a.toCharArray();
char bArray[] = b.toCharArray();
StringBuilder result = new StringBuilder("");
int aLength = a.length();
int bLength = b.length();
int minLength=0;
int maxLength=0;
int carry = 0;
int flag=-1;//flag=0则a长,flag=1则b长。
System.out.println(1>1);//false
if(aLength>bLength){
maxLength=aLength;
minLength=bLength;
flag=0;
}else if(aLength<bLength){
maxLength=bLength;
minLength=aLength;
flag=1;
}else{
flag=-1;
minLength=aLength;
maxLength=aLength;
}
//System.out.println((aArray[0] + bArray[0]+ 2));
for (int i = 0; i < minLength; i++) {
result.append((aArray[i] + bArray[i] + carry) % 2);
//System.out.println(result);
//System.out.println("carry/2:" + (aArray[i]-48 + bArray[i]-48 + carry) / 2);
if (((aArray[i]-48 + bArray[i]-48 + carry) / 2) >= 1) {
carry = 1;
} else {
carry = 0;
}
System.out.println(carry);
}
switch (flag){
case 1:{
for (int j=minLength;j<maxLength;j++){
result.append((bArray[j]-48+carry)%2);
if((bArray[j]-48+carry)/2>=1){
carry=1;
}else{
carry=0;
}
}
break;
}
case 0:{
for (int j=minLength;j<maxLength;j++){
result.append((aArray[j]-48+carry)%2);
if((aArray[j]-48+carry)/2>=1){
carry=1;
}else{
carry=0;
}
}
break;
}
}
if (carry==1) result.append('1');
return result.reverse().toString();
}
}
官方题解:实在简洁,没脸看了哈哈
class Solution {
public String addBinary(String a, String b) {
StringBuffer ans = new StringBuffer();
int n = Math.max(a.length(), b.length()), carry = 0;
for (int i = 0; i < n; ++i) {
carry += i < a.length() ? (a.charAt(a.length() - 1 - i) - '0') : 0;
carry += i < b.length() ? (b.charAt(b.length() - 1 - i) - '0') : 0;
ans.append((char) (carry % 2 + '0'));
carry /= 2;
}
if (carry > 0) {
ans.append('1');
}
ans.reverse();
return ans.toString();
}
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/JFETK5/solution/er-jin-zhi-jia-fa-by-leetcode-solution-fa6t/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
0和1的AciII码: ascii
char字符的运算:char跟int类型运算,计算的是ascii码
将字符串反转的几种方法:字符串反转