67.二进制求和
这道题和第二题基本类似,一一对应求和,大于2的进位。
1
class Solution {
2
public String addBinary(String a, String b) {
3
int i = a.length() -1 , j = b.length() -1;
4
int carry = 0;
5
StringBuffer sb = new StringBuffer();
6
while(i>-1 || j >-1){
7
int x = (i>-1) ? (a.charAt(i)=='0'?0:1) : 0;
8
int y = (j>-1) ? (b.charAt(j)=='0'?0:1) : 0;
9
int sum = x + y + carry;
10
carry = sum/2;
11
sb.append(sum%2);
12
if(i>-1)i--;
13
if(j>-1)j--;
14
}
15
if (carry > 0) {
16
sb.append(carry);
17
}
18
return sb.reverse().toString();
19
}
20
}
Copied!
最近更新 28d ago
复制链接