forked from xiaoningning/java-algorithm-2010
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddBinary.java
More file actions
42 lines (38 loc) · 1.15 KB
/
AddBinary.java
File metadata and controls
42 lines (38 loc) · 1.15 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
/*
* Given two binary strings, return their sum (also a binary string).
* For example,
* a = "11"
* b = "1"
* Return "100".
*/
public class AddBinary {
public static void main(String[] args) {
String s1 = "10";
String s2 = "110";
int result = string2Integer(s1, 2) + string2Integer(s2, 2);
System.out.println(toBinary(result));
result = Integer.parseInt(s1, 2) + Integer.parseInt(s2, 2);
System.out.println(Integer.toBinaryString(result));
}
public static int string2Integer(String s, int code) {
int len = s.length();
int result = 0;
for (int i = len -1 ; i >=0 ; i--) {
int temp = Integer.valueOf(s.charAt(i)-'0');
result += Math.pow(code, len-1-i) * temp;
}
return result;
}
public static String toBinary(int integer) {
StringBuilder builder = new StringBuilder();
int temp;
while (integer >= 0) {
temp = integer;
integer = (temp >> 1);
builder.append(temp % 2);
if(integer ==0)
break;
}
return builder.reverse().toString();
}
}