This content originally appeared on DEV Community and was authored by King coder
๐ 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
n
by10
usingMath.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
This content originally appeared on DEV Community and was authored by King coder

King coder | Sciencx (2025-07-24T04:43:43+00:00) ๐ Day 18 – DSA Problem Solving. Retrieved from https://www.scien.cx/2025/07/24/%f0%9f%9a%80-day-18-dsa-problem-solving/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.