Back to Interview Prep

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 1 if n is 0 (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, divide n by 10 using integer division and increment count.
  • Return: The count after 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 number1234
2Drop the last digit each pass1234 → 123 → 12 → 1 → 0
3Count the passescount++
4Number of digits4

Your 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.

You're viewing a free lesson. Sign up free to track your progress and unlock the full course.Sign up freeSign in