forked from lilong-dream/LeetCode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
89 lines (73 loc) · 1.58 KB
/
AddBinary.java
File metadata and controls
89 lines (73 loc) · 1.58 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Author: Li Long, [email protected]
// Date: Apr 18, 2014
// Source: http://oj.leetcode.com/problems/add-binary/
// Analysis: http://blog.csdn.net/lilong_dream/article/details/19995465
// Given two binary strings, return their sum (also a binary string).
// For example,
// a = "11"
// b = "1"
// Return "100".
public class AddBinary {
public String addBinary(String a, String b) {
char[] str1;
char[] str2;
if (a.length() >= b.length()) {
str1 = a.toCharArray();
str2 = b.toCharArray();
} else {
str1 = b.toCharArray();
str2 = a.toCharArray();
}
int m = str1.length;
int n = str2.length;
char[] sum = new char[m];
int i = m - 1;
char carry = '0';
--m;
--n;
while (n >= 0) {
if (str1[m] == '0' && str2[n] == '0') {
sum[i] = carry;
carry = '0';
} else if (str1[m] == '1' && str2[n] == '1') {
sum[i] = carry;
carry = '1';
} else {
if (carry == '1') {
sum[i] = '0';
} else {
sum[i] = '1';
}
}
--m;
--n;
--i;
}
while (m >= 0) {
if (str1[m] == '1') {
if (carry == '1') {
sum[i] = '0';
} else {
sum[i] = '1';
}
} else {
sum[i] = carry;
carry = '0';
}
--m;
--i;
}
String result = new String(sum);
if (carry == '1') {
return "1" + result;
}
return result;
}
public static void main(String[] args) {
String a = "11";
String b = "10";
AddBinary slt = new AddBinary();
String result = slt.addBinary(a, b);
System.out.println(result);
}
}