Last active
March 5, 2018 09:07
-
-
Save mwrites/44947486eb48e3a0b2cf833079bb2a34 to your computer and use it in GitHub Desktop.
Convert Binary, Base X, to Decimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func baseToDecimal(_ base: Int, notation : [Int]) -> Int { | |
return notation.reversed().enumerated().filter { $0.element == 1 }.reduce(into: 0) { | |
let powR = Int(pow(Float(base), Float($1.offset))) | |
$0 += powR | |
} | |
} | |
func decimal(_ d : Int, toBase base: Int) -> [Int] { | |
var res = [Int]() | |
var i = d | |
while i >= 1 { | |
let quotient = i / base | |
let remainder = i % base | |
if remainder > 0 { | |
res.append(1) | |
} else { | |
res.append(0) | |
} | |
i = quotient | |
} | |
return res.reversed() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment