e.g. for int n = 1234
I could create a string (s.valueOf(n))
, then I would define the array like this:
int[] array = new int[s.length()]; //this allocates memory for an array with 4 elements
Is there any other way to do this without using a string and only integers?
You can use Math#log10 to find the number of digits.
numOfDigits = (int)(Math.log10(n)+1);
Now you do:
int[] array = new int[numOfDigits];
Note that if n = 1999
, numOfDigits
will be 4. So you're allocating a memory for 4 integers and not 1999 integers.
But be careful, while reading the documentation of the method, you'll note:
If the argument is positive zero or negative zero, then the result is negative infinity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With