Skip to content

Instantly share code, notes, and snippets.

@macu
Created November 13, 2014 13:43
Show Gist options
  • Save macu/b805abf4ef83e48cf15b to your computer and use it in GitHub Desktop.
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.)
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