Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a6e5b4e

Browse files
Create 67.py
1 parent 517d584 commit a6e5b4e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

‎1-100/67.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution:
2+
def addBinary(self, a, b):
3+
"""
4+
:type a: str
5+
:type b: str
6+
:rtype: str
7+
"""
8+
# Resultant string
9+
result = ""
10+
# Indices for a and b
11+
aLength = len(a) - 1
12+
bLength = len(b) - 1
13+
# Carry
14+
carry = 0
15+
# Loop for all the characters in the strings
16+
while aLength >= 0 or bLength >= 0:
17+
# Sum of two bits
18+
totalSum = carry
19+
if aLength >= 0:
20+
totalSum += int(a[aLength])
21+
aLength -= 1
22+
if bLength >= 0:
23+
totalSum += int(b[bLength])
24+
bLength -= 1
25+
# Add the bit to te result
26+
result = str(totalSum % 2) + result
27+
# Modify carry
28+
carry = totalSum // 2
29+
# Final check if carry exists
30+
if carry > 0:
31+
result = str(1) + result
32+
return result

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /