0

I have a requirement where i need to find the number of digits in a integer. I have searched it and got some tricks. But i also developed a my own trick. I just want to know if it is correct way to know the number of digits in the integer.

for (int i = 1; i < 11; i++) {
    if (Math.abs(number) < (j = Math.pow(10, i))) {
        System.out.println("Number of Digits : "+i);
        break;
    }
}

I took 11 as limit because max integer is of 11 digits. Please let me know if it is a correct way or not.

please note that I dont have an option to use any string api.

  • 1
    It's too complicated. You can get the length `c` of any number `n` using: `int c = 0; while (n > 0) { n = n / 10; c++; }` which will also scale well and be pretty fast (faster than converting to a string and counting the length, about half the time). Do not use expensive functions like `pow` for such a simple task. – showp1984 Dec 02 '15 at 11:49

1 Answers1

5

Your solution won't perform well. It is too complicated as for a simple task. If the number was bigger, it would be really slow.

You should use:

String.valueOf(number).length()

Simple, easily readable and it will scale much better.

Jonasz
  • 1,617
  • 1
  • 13
  • 19
  • 2
    Note that this will consider the negative sign as a "digit" if `number` happens to be negative; the negative sign isn't a digit. – Andy Turner Dec 02 '15 at 10:56
  • Good point! Also commas and dots. Using replace method on the String (or an additional temporary String) would solve the problem. – Jonasz Dec 02 '15 at 10:59
  • 1
    If `number` is an `int`, as specified in the question, you won't have any commas or dots. – Andy Turner Dec 02 '15 at 11:00
  • Actually i have been told not to use String. – user3690370 Dec 02 '15 at 11:12
  • and even the biggest integer the loop wont take more that 11 iteration. – user3690370 Dec 02 '15 at 11:14
  • `String.valueOf(number).replaceAll("\\-?\\.?,?", "").length()` will get rid of `.`, `-` and (just for being complete, in case this is used somewhere else, like a user input) `,`. – showp1984 Dec 02 '15 at 11:30
  • If you cannot use String, you should run a while (or do-while) loop in which you will simply divide the number by 10 (casting to int may be required) and increase the length by 1 in each iteration. The loop stops when the number is equal to 0 (casting for example 3/10 to int will return 0). – Jonasz Dec 02 '15 at 12:05