-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution.java
More file actions
97 lines (96 loc) · 2.49 KB
/
Copy pathsolution.java
File metadata and controls
97 lines (96 loc) · 2.49 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
90
91
92
93
94
95
96
97
// 67. Add Binary
// https://leetcode.com/problems/add-binary/
// Easy | Java | Accepted 2026-08-24
// Runtime 2 ms | Memory 42.9 MB
class Solution {
public String addBinary(String a, String b) {
StringBuilder str = new StringBuilder();
int startA = a.length()-1;
int startB = b.length()-1;
int carry = 0;
while(startA>=0 && startB>=0)
{
if(a.charAt(startA)=='1' && b.charAt(startB)=='1')
{
int temp = 2+carry;
temp%=2;
str.append(temp);
carry = 1;
}
else if(a.charAt(startA)=='0' && b.charAt(startB)=='0')
{
str.append(carry);
carry = 0;
}
else
{
int temp = 1+carry;
temp%=2;
str.append(temp);
if(temp==0)
{
carry = 1;
}
else
{
carry = 0;
}
}
startA--;
startB--;
}
if(startB<0)
{
while(startA>=0)
{
if(a.charAt(startA)=='1')
{
int temp = 1+carry;
temp%=2;
str.append(temp);
if(temp==0)
{
carry = 1;
}
else
{
carry = 0;
}
}
else
{
str.append(carry);
carry = 0;
}
startA--;
}
}
if(startA<0)
{
while(startB>=0)
{
if(b.charAt(startB)=='1')
{
int temp = 1+carry;
temp%=2;
str.append(temp);
if(temp==0)
{
carry = 1;
}
else
{
carry = 0;
}
}
else
{
str.append(carry);
carry = 0;
}
startB--;
}
}
return carry == 1 ? str.append(carry).reverse().toString() : str.reverse().toString();
}
}