File tree 2 files changed +35
-0
lines changed
2 files changed +35
-0
lines changed Original file line number Diff line number Diff line change
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 number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments