Last active
October 15, 2019 05:58
-
-
Save andrewwoz/29c55c34dfa6e6020c94 to your computer and use it in GitHub Desktop.
[Number systems in Swift] #algorythms
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 numberToBaseString(number:Int,base:Int) -> String { | |
var inner_func:(Int,Int,String) -> String = { (_,_,_) -> String in return "" } | |
inner_func = { (number:Int,base:Int,result:String) -> String in | |
if number < base { | |
return String(number) + result | |
}else{ | |
let rem = number % base | |
let reducedNumber = (number - rem) / base | |
return inner_func(reducedNumber, base, String(rem) + result) | |
} | |
} | |
return inner_func(number, base, "") | |
} | |
func pow(p:Int,n:Int) -> Int { | |
if n == 0 { | |
return 1 | |
}else{ | |
return p * pow(p,n-1) | |
} | |
} | |
func baseStringToValue(string:String, base:Int) -> Int { | |
var inner_func:(String,Int,Int,Int) -> Int = { (_,_,_,_) -> Int in return 0 } | |
inner_func = { ( string:String, base, result,power) -> Int in | |
if string.isEmpty == true { | |
return result | |
}else{ | |
let char = string.getEnd | |
return inner_func(string.getStringWithoutEnd, base, pow(base, power) * char.toInt()! + result,power+1) | |
} | |
} | |
return inner_func(string,base,0,0) | |
} | |
println(numberToBaseString(21, 2)) //> "10101" | |
println(baseStringToValue(numberToBaseString(21, 2), 2)) //> 21 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment