Java Program to Count Number of Digits in an Integer - The Coding Shala

Home >> Java Programs >> Count Number of Digits in an Integer

 In this post, we will learn how to count the number of digits in an integer using a Java program.

Java Program to Count Number of Digits in an Integer

You have given an integer, return the number of digits in that using Java program. The given number is above 0.

Example 1:
Input: 34
Output: 2

Example 2:
Input: 01
Output: 1

Approach

When we divide a number by 10, we get one digit or we remove one digit from a given number so here we will be using a loop and divide the given number by 10 until it becomes 0.

Example: 

The number is 23, so after first iteration 

number = 23/10 = 2, and count = 1

second iteration => number = 2/10 = 0, count = 2.

Java Program: 

import java.util.Scanner;

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void printDigits(int num) {
        System.out.print("Number of Digits in " + num + " are: ");
        int count = 0;
        while (num > 0) {
            count++;
            num = num / 10;
        }
        System.out.println(count);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter an integer");
        int num = sc.nextInt();
        printDigits(num);
    }
}

Output: 

Enter an integer
011
Number of Digits in 11 are: 2


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

New Year Chaos Solution - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala