DEV Community

Cover image for πŸš€ Day 18 - DSA Problem Solving
King coder
King coder

Posted on • Edited on

πŸš€ Day 18 - DSA Problem Solving

πŸ“Œ Q1 :- Count Digits in a Number

Write a function that returns the number of digits in an integer n.

Example: For input -12345, the output should be 5.

πŸ’‘ Approach:

To count digits in a number:

  1. Check if the number is 0 β†’ return 1 (since 0 has one digit).
  2. Convert the number to a positive value using Math.abs(n) to handle negative inputs.
  3. Initialize a counter (count = 0).
  4. Use a loop:
    • While n > 0:
      • Divide n by 10 using Math.floor(n / 10).
      • Increment count.
  5. Return count.

πŸ§ͺ Corner Cases:

πŸ› οΈ Always write πŸ§ͺ Corner Cases: when solving any DSA problem.

It helps anticipate edge cases and ensures your solution handles all scenarios robustly.

Case Description
n = 0 Return 1 (since 0 has 1 digit)
Negative numbers (n = -123) Use Math.abs() to count digits correctly
Single-digit numbers Should return 1
Very large number Loop should handle large inputs efficiently
Non-integer inputs Not handled here, but worth validating in real-world cases

πŸ“₯ Input:

n = -12345
Enter fullscreen mode Exit fullscreen mode

πŸ“€ Output:

n = 5
Enter fullscreen mode Exit fullscreen mode

JavaScript Solution:


/**
 * Counts the number of digits in a number
 * @param {number} n - The input integer
 * @returns {number} - Number of digits
 */
function countDigits(n) {
    if (n === 0) return 1;

    n = Math.abs(n); // Handle negative numbers
    let count = 0;

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

    return count;
}

// Test Case
console.log("Digit count for -12345:", countDigits(-12345)); // Output: 5


Enter fullscreen mode Exit fullscreen mode

Top comments (0)