-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinSum.java
More file actions
50 lines (40 loc) · 1.09 KB
/
binSum.java
File metadata and controls
50 lines (40 loc) · 1.09 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
class Solution {
public String addBinary(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
int rem = 0;
String res = "";
int i = 0;
while(i < len1 || i < len2 || rem == 1)
{
int x = 0, y = 0;
if(i < len1)
{
x = s1.charAt(len1 - 1 - i) - '0';
}
if(i < len2)
{
y = s2.charAt(len2 -1 - i) - '0';
}
int result = (x + y + rem) % 2;
rem = (x + y + rem) / 2;
//System.out.println(i + " " + rem);
res = String.valueOf(result) + res;
i++;
}
int count = 0;
for(int j=0; j<res.length(); j++)
{
if(res.charAt(j) == '0')
{
count++;
}
else
{
break;
}
}
String ans = res.substring(count);
return ans;
}
}