8000 Add alghorithms for conversion from binary to decimal and decimal to … · TheAlgorithms/Swift@d0e8d66 · GitHub
[go: up one dir, main page]

Skip to content

Commit d0e8d66

Browse files
Add alghorithms for conversion from binary to decimal and decimal to binary
1 parent 2ce2905 commit d0e8d66

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import Foundation
2+
3+
/// This function accepts a binary number as String and converts it to decimal as Int.
4+
/// If it's not valid binary number (a.k.a not made only from digits), it returns nil.
5+
public func convertBinaryToDecimal(binary: String) -> Int? {
6+
if let _ = Int(binary) {
7+
var decimal = 0
8+
9+
let digits = binary.map { Int(String($0))! }.reversed()
10+
print(digits)
11+
var power = 1
12+
13+
for digit in digits {
14+
decimal += digit * power
15+
16+
power *= 2
17+
}
18+
19+
return decimal
20+
}
21+
22+
return nil
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/// This function accepts a non-negative number and returns its binary form as String.
2+
public func convertDecimalToBinary(decimal: Int) -> String {
3+
var binary = ""
4+
var decimal = decimal
5+
6+
while decimal != 0 {
7+
binary.insert(decimal % 2 == 0 ? "0" : "1", at: binary.startIndex)
8+
decimal /= 2
9+
}
10+
11+
return binary
12+
}

0 commit comments

Comments
 (0)
0