How to split an Int to its individual digits?

后端 未结 8 1291
误落风尘
误落风尘 2020-12-13 06:18

I am trying to split an Int into its individual digits, e.g. 3489 to 3 4 8 9, and then I want to put the digits in an Int array.

I have already tried putting the num

8条回答
  •  长情又很酷
    2020-12-13 07:12

    this code works:

    var number = "123456"
    var array = number.utf8.map{Int(($0 as UInt8)) - 48}
    

    this might be slower:

    var array = number.characters.map{Int(String($0))!}
    

    and if your number is less or equal than Int.max which is 9223372036854775807 here is the fastest variant (and if your number>Int.max you can split your long string that represents your number into 18-digit groups to make this variant work on large strings)

    var array2 = [Int]()
    var i = Int(number)!
    while i > 0 {array2.append(i%10); i/=10}
    array2 = array2.reverse()
    

提交回复
热议问题