-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
23 lines (22 loc) · 703 Bytes
/
AddBinary.java
File metadata and controls
23 lines (22 loc) · 703 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package leetcode.string;
/**
* @ClassName AddBinary
* @Description 二进制求和 https://leetcode-cn.com/problems/add-binary/
* @Author changxuan
* @Date 2020/11/21 下午11:31
**/
public class AddBinary {
public String addBinary(String a, String b) {
StringBuilder ans = new StringBuilder();
int ca = 0;
for(int i = a.length() - 1, j = b.length() - 1;i >= 0 || j >= 0; i--, j--) {
int sum = ca;
sum += i >= 0 ? a.charAt(i) - '0' : 0;
sum += j >= 0 ? b.charAt(j) - '0' : 0;
ans.append(sum % 2);
ca = sum / 2;
}
ans.append(ca == 1 ? ca : "");
return ans.reverse().toString();
}
}