- Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathadd-binary.py
More file actions
Latest commit
30 lines (28 loc) · 965 Bytes
/
Copy pathadd-binary.py
File metadata and controls
30 lines (28 loc) · 965 Bytes
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
# coding: utf-8
classSolution:
# @param {string} a a number
# @param {string} b a number
# @return {string} the result
defaddBinary(self, a, b):
# Write your code here
flag=0
ret=''
a_i, b_i=len(a) -1, len(b) -1
while (a_i>=0) and (b_i>=0):
va, vb=int(a[a_i]), int(b[b_i])
ret+=str((va+vb+flag) %2)
flag= (va+vb+flag) /2
a_i-=1
b_i-=1
c_i=-1
if (a_i>=0) or (b_i>=0):
c=aifa_i>=0elseb
c_i=a_iifa_i>=0elseb_i
whilec_i>=0:
ret+=str((int(c[c_i]) +flag) %2)
flag= (int(c[c_i]) +flag) /2
c_i-=1
ifflag:
ret+=str(flag)
returnret[::-1] # Python没有提供直接反转字符串的函数,用切片凑合一下吧。
# easy: http://lintcode.com/zh-cn/problem/add-binary/