0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swiftで整数Integerを桁数ごとに配列arrayに変換する方法

Posted at

アルゴリズム問題を解いている時に、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(整数)型で利用可能です。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?