Warm Up · Count Digit
Count the Number of Digits in an Integer
Problem Statement
Write a function countDigits(n) that takes an integer n and returns how many digits it contains.
Requirements
- Handles both positive and negative integers.
- Return
1ifnis0(since 0 is a single-digit number).
Examples
Input: 259→Output: 3
Input: -1035→Output: 4
Input: 0→Output: 1
Approach
- Handle Zero: If
n == 0, return 1 directly. - Convert to Positive: Use
abs(n)to ignore the sign. - Initialize a counter: Set
count = 0. - Loop: While
n > 0, dividenby 10 using integer division and incrementcount. - Return: The
countafter the loop finishes.
Time & Space Complexity
Time Complexity: O(d) - where d is the number of digits.
Space Complexity: O(1) - constant space.
Visualisation
1Enter a number
12342Drop the last digit each pass
1234 → 123 → 12 → 1 → 03Count the passes
count++4Number of digits
4Your solution
Solve it in JavaScript and print the answer with console.log(). Run to see your output, then Submit to check it against the test cases.
// Write your solution in JavaScript // Print the answer with console.log()
Console
No output yet. Use console.log() to print values here.
Write your own solution and press Submit once to unlock the answer.