How to Split an Integer into an Array of Digits

How do I separate an integer into separate digits in an array in JavaScript?

Why not just do this?

var n =  123456789;
var digits = (""+n).split("");

Convert an integer to an array of digits

The immediate problem is due to you using <= temp.length() instead of < temp.length(). However, you can achieve this a lot more simply. Even if you use the string approach, you can use:

String temp = Integer.toString(guess);
int[] newGuess = new int[temp.length()];
for (int i = 0; i < temp.length(); i++)
{
newGuess[i] = temp.charAt(i) - '0';
}

You need to make the same change to use < newGuess.length() when printing out the content too - otherwise for an array of length 4 (which has valid indexes 0, 1, 2, 3) you'll try to use newGuess[4]. The vast majority of for loops I write use < in the condition, rather than <=.

How to convert an integer into an array of digits

I'd go with

var arr = n.toString(10).replace(/\D/g, '0').split('').map(Number);

You can omit the replace if you are sure that n has no decimals.

splitting a number and storing in int array

Use n % 10 to get the last digit and n / 10 to get the others. For example, 5=12345%10, 1234=12345/10.

Convert integer to array:

int array[6];
int n = 123456;
for (int i = 5; i >= 0; i--) {
array[i] = n % 10;
n /= 10;
}

In general, vectors are preferred in C++, especially in this case since you probably don't know in advance the number of digits.

int n = 123456;
vector<int> v;
for(; n; n/=10)
v.push_back( n%10 );

Then v contains {6,5,4,3,2,1}. You may optionally use std::reverse to reverse it.

How to split an Int to its individual digits?

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]


Related Topics



Leave a reply



Submit