AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.

# corejava-programming: Write a program to print the number of digits of the number

 Write a program that declares and initializes an integer x. Then for this integer: - Print the number of digits of the number. For example, if x is 3564, it should print: Number of digits is 4 corejava x 353programming x 169 Posted On : 2018-02-21 21:39:00.0 5 Please refer below code snippet which contains 4 methods to fins the number of digits in a number in its complexity order low to high. public class DigitCalculator { int x; public static void main(String[] args) { DigitCalculator digitCal= new DigitCalculator(); digitCal.x=3564; System.out.println(digitCal.getNumberOfDigits(digitCal.x)); } /*Bulky but fastest approach*/ public int getNumberOfDigits(int number){ if(number < 100000){ if(number < 100){ if(number < 10) return 1; else return 2; }else{ if(number < 1000) { return 3; } else { if(number < 10000) return 4; else return 5; } } } else { if(number < 10000000) { if(number < 1000000) { return 6; } else { return 7; } } else { if(number < 100000000) { return 8; } else { if(number < 1000000000) { return 9; } else { return 10; } } } } } /*Second Best Approach*/ public int getNumberOfDigitsByPowerOf2(int number){ int length = 1; if (number >= 100000000) { length += 8; number /= 100000000; } if (number >= 10000) { length += 4; number /= 10000; } if (number >= 100) { length += 2; number /= 100; } if (number >= 10) { length += 1; } return length; } /*3rd best approach*/ public int getNumberOfDigitsByWhile(int number){ int length = 0; long temp = 1; while(temp <= number){ length++; temp *= 10; } return length; } /*Simple and short*/ public int getNumberOfDigitsByLogarithm(int number){ return (int) (Math.log10(number) + 1); } } Posted On : 2018-02-22 22:24:49 Satisfied : 0 Yes  0 No Garima Gupta 596129551595Reply This Thread 0 