-3

This question includes numbers with leading zeros and numbers which normally counted as hexadecimal(like 09).Assume user input is integer,because i pass number to some function as integer.

For example

  • if user inputs 5 i should get 1
  • if user inputs 0005 i should get 4
  • if user inputs 09 i should get 2

(Note)Below method does not work:

String.valueOf(integer).length()
Wardruna
  • 198
  • 4
  • 23

2 Answers2

1

The user input will probably be a String already, so you could just use String.length(). For example:

public static void main(String... args) {
    Scanner in = new Scanner(System.in);
    String number = in.next();
    int numDigits = number.length();
    System.out.println(numDigits);
}

If the input were an integer, it couldn't have leading zeros. If the initial input had zeros and you converted it to an integer at some point, you lost this information.

Anderson Vieira
  • 8,919
  • 2
  • 37
  • 48
1

This only works if the number you want is a String. You don't have 0005 integer numbers unless it is not an integer, it is a String instead. You have to save those numbers as a String instead of a int for this to work. Then you can use the .length() method

alexandre1985
  • 1,056
  • 3
  • 13
  • 31