InterviewSolution
Saved Bookmarks
| 1. |
Write a program in Java to count the digits in a number. |
|
Answer» Let us consider the number 12345. This is a 5 digit number. The number of digits can be counted as follows: In the image above, we have shown the way of extracting the digits of a number. However, in our questions, we just need to count the digits in the number. So, we have to count the number of times we can divide our input number by 10 before it becomes 0. Let us write the code based on the above algorithm. Java Program to Count the Number of Digits in a Number. import java.util.*;class Main { public static int countDigits(int n) { if(n == 0) return 1; //if a negative number is entered if(n < 0) n = -n; int res = 0; while(n != 0) { n = n/10; res++; } return res; } public static void main(String args[]) { // Your code goes here Scanner scn = new Scanner(System.in); int n = scn.nextInt(); //input the number System.out.println("The number of digits in " + n + " are: " + countDigits(n)); } } Output
Output: The number of digits in 1234 is: 4
Output: The number of digits in 0 is: 1
Output: The number of digits in -12345 is: 5
|
|