So this probably would be easy if done like this
public static [] nums(int j)
{
int num = 12345;
int[]thenums = [5];
for(int i=0; i<5; i++)
{
thenums[4-i] = num%10;
num = num/10;
}
return the nums
}
i get {1,2,3,4,5}
but for some reason if the number starts with a 0 then it does not work
how to make this work if the number were
int num = 02141;
thanks
EDIT: Doh… I’d completely forgotten about octal literals. That explains why the value is showing up differently. (
02141is treated as an octal literal; it’s not the same value as2141.)However, it sounds like the OP wants to “remember” the number of leading zeroes in a number. There’s no way of doing that as an integer, because it’s just remembering a value. What’s the difference between seeing “3” birds and seeing “0000003” birds?
If you have a number representation where the leading zeroes are important, you’re not just talking about an integer quantity, which is all that an
intrepresents.Where are you getting your input from? It sounds like you should just be maintaining it as a string from the start.
If you always want 5 digits, that’s easy to do – and your current code should do it (when amended to actually compile) – something like this:
Now that’s hard-coded to return 5 digits. If you don’t know the number of digits at compile-time, but you will know it at execution time, you could pass it into the method: