Given a number N, the task is to return the count of digits in this number.
![](https://miro.medium.com/v2/resize:fit:650/1*kVABqEK3Z_7BVfuJVmmluw.png)
There are two approaches to get the count of digits in the number N.
Let us see both the approaches:
Approach 1:
We can convert the number into a String and get the length of the string to get the number of digits in the number.
Time Complexity = O(1)
Space Complexity = O(1)
package com.practice.basicprograms;
public class CountOfDigitsinNumber {
public static void main(String[] args) {
int number=18192;
String N=Integer.toString(number);
int length=N.length();
System.out.println(length);
}
}
Approach 2:
- Initialize a count variable and increment it by using loop
- Run a while loop until N becomes equal or less than 0
- Divide N by 10, so that last digit will get eliminated with each iteration
- Return the count variable to get the number of digits
![](https://miro.medium.com/v2/resize:fit:875/1*moMTeT2LhhOT197AH-tccA.png)
package com.practice.basicprograms;
public class CountOfDigitsinNumberUsingLoop {
public static void main(String[] args) {
int n=18192;
CountOfDigitsinNumberUsingLoop counts=new CountOfDigitsinNumberUsingLoop();
System.out.println(counts.countofdigits(n));
}
public int countofdigits(long number){
int count = 0;
while(number!=0){
number=number/10;
count++;
}
return count;
}
}
Time Complexity: O(count of digits)
Space Complexity: O(1)
Happy Coding!!!!