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.
source share