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

eg. for int n = 1234 I could create a string (s.valueOf(n)) , then I would define an array as follows:

 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?

+4
source share
5 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. Thus, you allocate memory for 4 integers, not 1999 integers.

But be careful reading the documentation for this method, you will notice:

If the argument is positive zero or negative zero, then the result is negative infinity.

+13
source

I assume you are talking about Java, therefore:

  int value = myValue; for (int noOfDigits = 1; Math.abs(value) >= 1; ++noOfDigits) { value /= 10; } int[] array = new int[noOfDigits]; 

This does not include a space for the leading character if the number is negative, but you can easily check this condition and increment noOfDigits by one.

+5
source

Use log function to find no. digits.

 int size = (int)Math.log10(1234)+1; int[] array = new int[size]; 
+2
source

In my opinion, you can do the following to get the number of digits

  int n = 12345; int count = 1; while(n>10){ n = n/10; count++; } int[] array = new int[count]; 
0
source
 if (n>0){ numberOfDigets = (int)(Math.log10(n)+1); } else if (n < 0){ numberOfDigets = (int)(Math.log10(Math.abs(n))+1); } else { numberOfDigets = 1; } 

If n is greater, then zero uses the Math.log10 function, as Marun Marun wrote. If n is less than zero, use the Math.abs function to get a positive value. If you want to allocate space for - add 2 instead of 1. The else clause is for the case when n is zero and sets numberOfDigets to 1.

If the extra java function call does not matter, use this code. if (n! = 0) {numberOfDigets = (int) (Math.log10 (Math.abs (n)) + 1); } else {numberOfDigets = 1; }

Math.abs(n) will always return a positive version of n. The value to be observed is Integer.min_value beacuse, whose value will still be negative, but that's another question.

0
source

Source: https://habr.com/ru/post/1479510/


All Articles