Calculate Length of Integer in Java

Siddharth Swami Jan 30, 2023 Oct 10, 2021
  1. Use the for Loop to Calculate the Length of an Integer in Java
  2. Use the Math.log10() Function to Calculate the Length of an Integer in Java
  3. Use the toString() Function to Calculate the Length of an Integer in Java
Calculate Length of Integer in Java

In this tutorial, we calculate the number of digits in an integer in Java.

Use the for Loop to Calculate the Length of an Integer in Java

First, we will see a simple iterative solution for this. We will divide the integer by 10, storing the count in each iteration until the number equals zero.

The below code demonstrates the above method.

public class Digits {
    static int count_digit(int x)
    {
        int count = 0;
        while (x != 0) {
            x = x / 10;
            ++count;
        }
        return count;
    }
    public static void main(String[] args)
    {
        int x = 345;
        System.out.print(count_digit(x));
    }
}

Output:

3

We can also implement the above logic using a divide and conquer with recursion.

Use the Math.log10() Function to Calculate the Length of an Integer in Java

Now let’s see the log-based solution for this. We will be using the logarithm of base 10 for counting the number of the digits in an integer. This method will work only on positive integers. We will be importing the java.util class from which we will use the Math.log10() function.

See the code below.

import java.util.*;
 
public class Digits {
 
    static int count_digit(int x)
    {
        return (int)Math.floor(Math.log10(x) + 1);
    }
 
    public static void main(String[] args)
    {
        int x = 345;
        System.out.print(count_digit(x));
    }
}    

Output:

3

Use the toString() Function to Calculate the Length of an Integer in Java

Another method is to change the integer into a string and then calculate its length. We will use the toString() function from the java.util package to convert the integer to a string. The length() method returns the length of the string.

The below code demonstrate the above code.

import java.util.*;
public class Digits {
    static void count_digits(int x)
    {
        String dig = Integer.toString(x);
        System.out.println(+dig.length());
    }
    public static void main(String args[])
    {
        int x = 345;
        count_digits(x);
    }
}

Output:

3

Related Article - Java Int