I have been writing a program to count the number of zeros in a number.
I implemented the following:
let num = 00012340000, count = 0, digits;
digits = num.toString().split("");
console.log(digits)
for (let i = 0; i < digits.length; i++) {
if (parseInt(digits[i]) == 0) {
count++
}
}
console.log(count)
The entire digit's value changes and the program automatically strip off the zeros from the front.
[
'2', '7', '3',
'6', '1', '2',
'8'
]
Can anyone please suggest what is responsible for this behavior?
If you want to count the leading zeros, you can use a while loop and check the character at the current position.
/**
* Counts the number of leading zeros in a numeric string.
* @param {string} num - number with zero-or-more leading zeros
* @returns {number} the amount of leading zeros
*/
const countLeadingZeros = (num) => {
let count = 0;
while (count < num.length && num.charAt(count) === '0') { count++; }
return count;
}
console.log(countLeadingZeros('00012340000')); // Pass-in a string value