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

  • For Positive Number
Input: 1234
Output: The number of digits in 1234 is: 4
  • For 0
Input: 0
Output: The number of digits in 0 is: 1
  • For Negative Number
Input: -12345
Output: The number of digits in -12345 is: 5


  • Corner Cases You Might Miss: We have used the loop and carried on iterations till the number becomes 0. What if the number was already 0? It still has 1 digit. So, we have handled that separately. Also, to avoid any confusion, the negative numbers are converted to positive in our function and then we calculate their number of digits.


  • Time Complexity: O(log10N) where N is the input number. This is because we keep dividing the number by 10.


  • Auxiliary Space: O(1) as we have not used any extra space.




Discussion

No Comment Found