π 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:
- Check if the number is
0β return1(since 0 has one digit). - Convert the number to a positive value using
Math.abs(n)to handle negative inputs. - Initialize a counter (
count = 0). - Use a loop:
- While
n > 0:- Divide
nby10usingMath.floor(n / 10). - Increment
count.
- Divide
- While
- 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
π€ Output:
n = 5
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


Top comments (0)