Skip to content

Commit 508e547

Browse files
Merge pull request #31 from wiktorwojcik112/master
Add algorithms for binary to decimal and decimal to binary conversion
2 parents 7097b14 + da6daec commit 508e547

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

DIRECTORY.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
# List of all files
22

33
## Algorithms
4+
* conversion
5+
* [Binary to decimal](https://github.com/TheAlgorithms/Swift/blob/master/algorithms/conversion/binary-to-decimal.swift)
6+
* [Decimal to binary](https://github.com/TheAlgorithms/Swift/blob/master/algorithms/conversion/decimal-to-binary.swift)
47
* Ai
58
* Minimax
69
* Sources
Lines changed: 23 additions & 0 deletions
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+
}
Lines changed: 12 additions & 0 deletions
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)