アルゴリズム問題を解いている時に、123456のようなIntの各々の桁数を求める方法を調べた際のメモ。
以下のようなExtensionを使えば整数Integerから簡単に桁数ごとに配列Arrayを生成できます。
extension BinaryInteger {
var digits: [Int] {
String(describing: self).compactMap { Int(String($0)) }
}
}
let number: Int = 123456
print(number.digits) // [1, 2, 3, 4, 5, 6]
Int(123).digits
Int32(123).digits
Int8(123).digits
BinaryIntegerとは全てのInteger(整数)型が準拠しているprotocolなので、全てのInteger(整数)型で利用可能です。