12. Count Digits in a Number

Difficulty:EasyPattern:Number ManipulationTime:O(d)Space:O(1)

Given an integer, count how many digits it contains.

How It Works & Algorithmic Design

For a positive integer, repeatedly divide the number by 10:

  1. Handle 0 as a special case because it contains one digit.
  2. Convert negative values to their absolute value.
  3. Repeatedly divide by 10 using integer division.
  4. Increment the digit counter after every division.
  5. Stop when the number becomes 0.

Why This Approach Works Best

Each iteration removes one decimal digit. Therefore the time complexity is $O(d)$ where $d$ is the number of digits, with $O(1)$ space.

Example Walkthrough

Input

5832

The number contains four digits.

Division

5832 -> 583 -> 58 -> 5 -> 0

Each division by 10 removes the last digit.

Output

4

Four divisions were required.

Answer: Count digits

function countDigits(n) {
  n = Math.abs(n);
  if (n === 0) return 1;

  let count = 0;
  while (n > 0) {
    n = Math.floor(n / 10);
    count++;
  }
  return count;
}

Repeatedly remove the last digit using division by 10.

Key Takeaways
  • Integer division by 10 removes the last decimal digit.

  • Zero must be handled separately because 0 contains one digit.

  • The algorithm uses constant auxiliary space.