How can I find the amount of digits in an integer? Mathematically, and by using functions if there are any.
I don't really know how to do that, since I'm a somewhat beginner.
CodePudding user response:
In Java, I would convert the integer to a string using the .toString() function and then use the string to determine the number of digits.
Integer digit = 10000;
Integer digitLenght = digit.toString().length();
CodePudding user response:
Another option would be to do it iteratively by dividing number by 10
, until result is 0
.
int number = ...;
int count = 1;
while ((number /= 10) != 0) {
count ;
}
CodePudding user response:
There are many ways to calculate the number of digits in a number. The main difference between them is how important performance is to you. The first way is to translate a number into a string and then take its length:
public static int countDigitsFoo(int x) {
if (x == Integer.MIN_VALUE) {
throw new RuntimeException("Cannot invert Integer.MIN_VALUE");
}
if (x < 0) {
return countDigitsFoo(-x); // 1; if you want count '-'
}
return Integer.toString(x).length();
}
This method is bad for everyone, except that it is easy to write. Here there is an extra allocation of memory, namely the translation of a number into a string. That with private calls to this function will hit performance very hard.
The second way. You can use integer division and sort of go by the number from right to left:
public static int countDigitsBoo(int x) {
if (x == Integer.MIN_VALUE) {
throw new RuntimeException("Cannot invert Integer.MIN_VALUE");
}
if (x < 0) {
return countDigitsBoo(-x); // 1; if you want count '-'
}
int count = 0;
while (x > 0) {
count ;
x /= 10;
}
return count;
}
but even this method can be improved. I will not write it in full, but I will give part of the code. A bunch of conditions may turn out to be faster than the division operation. Here it is already necessary to measure the speed in your environment.
public static int countDigitsHoo(int x) {
if (x == Integer.MIN_VALUE) {
throw new RuntimeException("Cannot invert Integer.MIN_VALUE");
}
if (x < 0) {
return countDigitsHoo(-x); // 1; if you want count '-'
}
if (x < 10) {
return 1;
}
if (x < 100) {
return 2;
}
if (x < 1000) {
return 3;
}
// ...
return 10;
}
You also need to decide what is the number of digits in the number. Should I count the minus sign along with this? Also, in addition, you need to add a condition on Integer.MIN_VALUE because
Integer.MIN_VALUE == -Integer.MIN_VALUE
This is due to the fact that taking a unary minus occurs by -x = ~x 1 at the hardware level, which leads to "looping" on -Integer.MIN_VALUE