Recursive solution for counting number of zeroes in a number is as below:
const number = 3004;
const countZeroes = function (num) {
if (num == 0) {
return;
}
if (num % 10 == 0) {
count += 1;
}
countZeroes(parseInt(num / 10));
}
let count = 0;
countZeroes(3004);
console.log('the result ', count);
The above solution works fine when we use count as a global variable. But it does not work when count is passed as a reference variable. Please find the solution below:
const number = 3004;
const countZeroes = function (num, count) {
if (num == 0) {
return count;
}
if (num % 10 == 0) {
count += 1;
}
countZeroes(parseInt(num / 10));
}
let count = 0;
const result = countZeroes(3004, count);
console.log('the result ', result);
Does javascript only allows pass by value and not by reference. Please let me know.