Program to count digits in an integer!!!

Sri Priya P Kulkarni
2 min readMay 24, 2024

--

Given a number N, the task is to return the count of digits in this number.

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:

  1. Initialize a count variable and increment it by using loop
  2. Run a while loop until N becomes equal or less than 0
  3. Divide N by 10, so that last digit will get eliminated with each iteration
  4. Return the count variable to get the number of digits
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!!!!

--

--

Sri Priya P Kulkarni

SDET| Blogger! | Automation Enthusiast! | On a journey of Continuous learning.... !