Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I allocate memory for an array of digits (int) of a number with the length being equal to the number of digits of that number?

Tags:

java

arrays

int

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?

like image 832
constant Avatar asked Nov 30 '22 03:11

constant


1 Answers

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.

like image 83
Maroun Avatar answered Dec 05 '22 02:12

Maroun