-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAddBinary.java
More file actions
29 lines (28 loc) · 833 Bytes
/
AddBinary.java
File metadata and controls
29 lines (28 loc) · 833 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class AddBinary {
/**
* 二进制相加
*/
public static String addBinary(String a, String b) {
StringBuilder sb = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;
while (i >= 0 || j >= 0) {
int sum = carry;
if (j >= 0) sum += b.charAt(j--) - '0';
if (i >= 0) sum += a.charAt(i--) - '0';
sb.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) sb.append(carry);
return sb.reverse().toString();
}
public static void main(String[] args) {
// 17 -> 1
// 9 -> 1
//4 -> 0
// 2 -> 0
// 1 -> 0
// 0 -> 1
// 1 + 16
System.out.println(addBinary("11", "1")); // 12 + 5 = 17
}
}