+ 1
How to count the number of digits of a number?
Just like length() but only for integers
5 ответов
+ 5
If you want to use length() method then you can first convert the number to string and then use length()
e.g. int a = 13445;
String s = String.valueOf(a);
int l = s.length();
+ 5
Miguel Ángel Your method appears to return a count of 0 for the value 0, which has 1 digit.
+ 3
Static int countDigit(long n)
{
int count = 0;
while (n != 0) {
n = n / 10;
++count;
}
return count;
}
Then in the main you call the method and pass the number by parameters.
+ 2
Rishi Anand
You can shorten it:
int number = 1234;
int length = Integer.toString(number).length();
//or String.valueOf(number).length();
Miguel Ángel
Another problem: negative numbers
Btw: if you use the string version it counts also the minus sign.
123 => length = 3
-123 => length = 4
0
Hatsy Rei true, it's better then that in while, the condition have the length of the parameters i think.
Good job.