Skip to content

Commit 08ec0b8

Browse files
committed
AddBinary67
1 parent b42bd0b commit 08ec0b8

1 file changed

Lines changed: 31 additions & 1 deletion

File tree

src/AddBinary67.java

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ private void addBinary(String a, String b, int i, int j, int carry, StringBuilde
4646
}
4747

4848

49-
5049
public String addBinary3(String a, String b) {
5150
StringBuilder sb = new StringBuilder();
5251
int carry = 0;
@@ -83,4 +82,35 @@ public String addBinary3(String a, String b) {
8382
return sb.toString();
8483
}
8584

85+
public String addBinary4(String a, String b) {
86+
char[] intToChar = new char[]{'0', '1'};
87+
int len = Math.max(a.length(), b.length());
88+
char[] res = new char[len + 1];
89+
int carry = 0;
90+
int s = len;
91+
int i = a.length() - 1;
92+
int j = b.length() - 1;
93+
while (i >= 0 && j >= 0) {
94+
int sum = charToInt(a.charAt(i--)) + charToInt(b.charAt(j--)) + carry;
95+
carry = sum >> 1;
96+
res[s--] = intToChar[sum & 1];
97+
}
98+
while (i >= 0) {
99+
int sum = charToInt(a.charAt(i--)) + carry;
100+
carry = sum >> 1;
101+
res[s--] = intToChar[sum & 1];
102+
}
103+
while (j >= 0) {
104+
int sum = charToInt(b.charAt(j--)) + carry;
105+
carry = sum >> 1;
106+
res[s--] = intToChar[sum & 1];
107+
}
108+
res[0] = intToChar[carry];
109+
return res[0] == '0' ? (new String(res)).substring(1) : new String(res);
110+
}
111+
112+
private int charToInt(char c) {
113+
return c - '0';
114+
}
115+
86116
}

0 commit comments

Comments
 (0)