Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an Int to its individual digits?

Tags:

swift

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 number into a string and then iterating over each digit, but it doesn't work:

var number = "123456"  var array = [Int]()  for digit in number {     array.append(digit) } 

Any ideas?

like image 708
Do2 Avatar asked May 23 '15 18:05

Do2


People also ask

How do you separate numbers into digits in Excel?

This section will show a formula to split selected number cells into individual digits in Excel. 1. Select a blank cell (says cell C1) for locating the first split digit of number in cell A1, then enter formula =MID($A1,COLUMN()-(COLUMN($C1)- 1),1) into the formula bar, and then press the Enter key.

How do you divide a number into equal parts?

Approach: There is always a way of splitting the number if X >= N. If the number is being split into exactly 'N' parts then every part will have the value X/N and the remaining X%N part can be distributed among any X%N numbers.


2 Answers

We can also extend the StringProtocol and create a computed property:

edit/update: Xcode 11.5 • Swift 5.2

extension StringProtocol  {     var digits: [Int] { compactMap(\.wholeNumberValue) } } 

let string = "123456" let digits = string.digits // [1, 2, 3, 4, 5, 6] 

extension LosslessStringConvertible {     var string: String { .init(self) } }  extension Numeric where Self: LosslessStringConvertible {     var digits: [Int] { string.digits } } 

let integer = 123 let integerDigits = integer.digits // [1, 2, 3]  let double = 12.34 let doubleDigits = double.digits   // // [1, 2, 3, 4] 

In Swift 5 now we can use the new Character property wholeNumberValue

let string = "123456"  let digits = string.compactMap{ $0.wholeNumberValue } // [1, 2, 3, 4, 5, 6] 
like image 190
Leo Dabus Avatar answered Sep 20 '22 06:09

Leo Dabus


A solution without having to convert the int to string....

Example

1234%10 = 4 <- 1234/10 = 123 123%10 = 3 <- 123/10 = 12 12%10 = 2 <-  12/10 = 1 1%10 = 1 <-  var num = 12345 var arrayInt = [Int]() arrayInt.append(num%10) while num >= 10 {   num = num/10   arrayInt.insert(num%10, at: 0) } 
like image 38
Tiago Couto Avatar answered Sep 23 '22 06:09

Tiago Couto