Skip to content

Commit d8596c5

Browse files
committed
add binary
1 parent f148f70 commit d8596c5

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

Add Binary/Add Binary.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#! /usr/bin/env python
2+
# -*- coding: utf-8 -*-
3+
4+
class Solution(object):
5+
def addBinary(self, a, b):
6+
"""
7+
:type a: str
8+
:type b: str
9+
:rtype: str
10+
"""
11+
result = ""
12+
sumVal = 0
13+
achars = list(a)
14+
bchars = list(b)
15+
i = len(achars) - 1
16+
j = len(bchars) - 1
17+
evl = 0
18+
19+
while i >= 0 or j >= 0 or evl>0:
20+
sumVal = evl
21+
if i >= 0:
22+
sumVal += int(achars[i])
23+
i -= 1
24+
if j >= 0:
25+
sumVal += int(bchars[j])
26+
j -= 1
27+
28+
evl = sumVal // 2
29+
sumVal = sumVal % 2
30+
result = str(sumVal) + result
31+
32+
return result
33+
34+
35+
a = Solution()
36+
b = a.addBinary('1','1')
37+
print(b)

Add Binary/Add Binary.swift

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import Foundation
2+
3+
/*
4+
Given two binary strings, return their sum (also a binary string).
5+
*/
6+
class Solution {
7+
func addBinary(_ a: String, _ b: String) -> String {
8+
var result = ""
9+
var sum = 0
10+
let aChars = Array(a.characters)
11+
let bChars = Array(b.characters)
12+
var i = aChars.count - 1
13+
var j = bChars.count - 1
14+
var evl = 0
15+
16+
while i>=0 || j >= 0 || evl > 0 {
17+
sum = evl // 进1位
18+
if i>=0 {
19+
sum += Int(String(aChars[i]))!
20+
i -= 1
21+
}
22+
if j>=0 {
23+
sum += Int(String(bChars[j]))!
24+
j -= 1
25+
}
26+
// sum 0, 1, 2
27+
// evl 0, 1
28+
evl = sum / 2
29+
sum = sum % 2
30+
result = String(sum) + result
31+
}
32+
33+
return result
34+
}
35+
}
36+
37+
let a = Solution()
38+
let b = a.addBinary("11", "10")
39+
40+
41+
42+
43+

0 commit comments

Comments
 (0)