Created
November 13, 2014 13:43
-
-
Save macu/b805abf4ef83e48cf15b to your computer and use it in GitHub Desktop.
Method in Swift for extracting the digits from an integer. (Negative integers not supported.)
This file contains 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
extension Int { | |
/// Returns the digits of the number in the given base. | |
/// The array of digits is ordered from most to least significant. | |
func digits(base: Int = 10) -> [Int] { | |
if self < base { | |
return [self] | |
} | |
var n = self | |
var d: [Int] = [] | |
while n > 0 { | |
d.insert(n % base, atIndex: 0) | |
n /= base | |
} | |
return d | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment