+ 1

How to count the number of digits of a number?

Just like length() but only for integers

20th Oct 2019, 1:05 PM
David Allen Dominden
David Allen Dominden - avatar
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();
20th Oct 2019, 1:14 PM
Rishi Anand
Rishi Anand - avatar
+ 5
Miguel Ángel Your method appears to return a count of 0 for the value 0, which has 1 digit.
20th Oct 2019, 1:28 PM
Hatsy Rei
Hatsy Rei - avatar
+ 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.
20th Oct 2019, 1:12 PM
Miguel Ángel
Miguel Ángel - avatar
+ 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
20th Oct 2019, 6:33 PM
Denise Roßberg
Denise Roßberg - avatar
0
Hatsy Rei true, it's better then that in while, the condition have the length of the parameters i think. Good job.
20th Oct 2019, 3:32 PM
Miguel Ángel
Miguel Ángel - avatar