Count digits in a number

Count digits in a number

Easy Java Control Flow 19 views
Explanation Complexity

Problem Statement

Task: return how many digits are in an integer. Handle 0 properly.

Input Format

An integer n.

Output Format

An integer: number of digits in n.

Constraints

• n can be 0, positive, or negative

• Must handle 0 correctly

Concept Explanation

Digits are counted by dividing the number by 10 repeatedly.
Special case: 0 has exactly one digit.

Step-by-Step Explanation

1.Read integer n.

2.If n == 0, return 1.

3.If n is negative, make it positive.

4.Initialize count = 0.

5.While n > 0:

• Increment count.

• Divide n by 10.

6.After loop ends, return count.

Concept Explanation

Digits are counted by dividing the number by 10 repeatedly.
Special case: 0 has exactly one digit.

Step-by-Step Explanation

1.Read integer n.

2.If n == 0, return 1.

3.If n is negative, make it positive.

4.Initialize count = 0.

5.While n > 0:

• Increment count.

• Divide n by 10.

6.After loop ends, return count.

Input / Output Format

Input Format
An integer n.
Output Format
An integer: number of digits in n.
Constraints
• n can be 0, positive, or negative

• Must handle 0 correctly

Examples

Input:
0
Output:
1

Example Solution (Public)

Java
static int countDigits(int x){if(x==0) return 1;int n=x<0?-x:x;int c=0;while(n>0){c++;n/=10;}return c;}

Official Solution Code

static int countDigits(int x){if(x==0) return 1;int n=x<0?-x:x;int c=0;while(n>0){c++;n/=10;}return c;}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.