Count Digits - codepath/compsci_guides GitHub Wiki

TIP102 Unit 1 Session 2 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 10 mins
  • 🛠️ Topics: Mathematical Computation, Loop

U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • The function count_digits() should take a non-negative integer n and return the number of digits in n.
HAPPY CASE
Input: 964
Expected Output: 3

Input: 0
Expected Output: 1

EDGE CASE
Input: 12345678901234567890
Expected Output: 20

P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Use a loop to divide the number by 10 repeatedly until it becomes 0, while counting the number of iterations.

1. Define the function `count_digits(n)`.
2. Handle the special case when `n` is 0, directly returning 1.
3. Initialize a counter variable `count` to 0.
4. Use a while loop to divide `n` by 10 until `n` is 0:
   - Increment the counter `count` in each iteration.
5. Return the counter `count` as the number of digits.

⚠️ Common Mistakes

  • Not accounting for the special case when n is 0.
  • Forgetting to update the counter correctly in the loop.

I-mplement

Implement the code to solve the algorithm.

def count_digits(n):
    # Special case for 0
    if n == 0:
        return 1
    
    count = 0
    while n > 0:
        n //= 10
        count += 1
    
    return count