- Home /
Split each number in an int without converting to char and string first?
I would like to separate each number in an int variable to an array (similar to ToCharArray
). Let's say I have the number 123, then I'd like to put that into an array which looks like this: [0,0,0,0,1,2,3]
(as the final step).
Is there a way of achieving this without converting it to a string first? Performance is key as it has to run on an iPhone 3GS as minimum.
Doing something like this works, but I'm afraid it might be way to intense (what do you think?):
private var numbers : int = 1234567; //This can be 0 to 9999999
private var numArray : int[] = [0,0,0,0,0,0,0]; //The array to store the int numbers
function Start () {
InvokeRepeating("NumToArray", 0, 0.1); //Or some other acceptable repeated value
}
function NumToArray () {
var numString : String = numbers.ToString();
var numCharArray : char[] = numbers.ToCharArray();
var pos : int = 6;
for (var i : int = numCharArray.Length-1; i>=0; i--) {
numArray[pos] = parseInt(scoreStringArray[i].ToString());
pos--;
}
}
I know this question is very old - by I wondered if you figured out you could just take off the ASCII code of a 0 from the char at position scoreStringArray[x] and save yourself that parsing... Any way, just a thought.
Sorry about the late answer, but that is very clever! It never got to the point of actual need of implementation so therefore there never were a crucial need of solution. :-) This could be a good way of making a digital clock display its numbers, or some other limited display area (pinball score/text display for instance).. Will try some fun stuff out with your suggestion!
Answer by tomka · May 29, 2012 at 06:53 AM
Mod operator
e.g.:
int num = 123;
int ones = 123 % 10;
int tens = 123 % 100 - ones;
int hundreds = 123 % 1000 - tens - ones;
int thousands = 123 % 10000 - hundres - tens - ones;
etc.
I'm sure with a little bit of thinking you could write this up as a recursive function that will fill out an array.
I'll have a look into it, perhaps there's a clever way down that path too.
No need to recurse, you could do it in a simple while
loop: store num%10
in the 'ones' index, divide num by 10, decrease index, repeat until num==0.