从最长的最后一位往前加,保证是从最低位加到最高位。
搞不懂,之前都可以通过的。
public String addBinary(String a, String b) {
String result = "";
int lenA = a.length();
int lenB = b.length();
int maxLen = lenA > lenB ? lenA : lenB;
int curr = 0;
int currA = 0;
int currB = 0;
int carry = 0;
for(int i = 0; i < maxLen; i++){
//current bit of string a
if(lenA > 0) currA = a.charAt(lenA - 1) - '0';
else currA = 0;
//current bit of string b
if(lenB > 0)currB = b.charAt(lenB - 1) - '0';
else currB = 0;
//addition
curr = (currA + currB + carry)%2;
carry = (currA + currB + carry)/2;
result = curr + result;
lenA--; lenB--;
}
if (carry == 1) return "1" + result;
else return result;
}
}
No comments:
Post a Comment