ปัญหา
เราต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลข n ฟังก์ชันควรนับและคืนค่าจำนวนครั้งที่เราต้องใช้เลข 9 ขณะนับจาก 0 ถึง n
ตัวอย่าง
โค้ดตัวอย่างดังนี้:
const num = 100;
const countNine = (num = 0) => {
const countChar = (str = '', char = '') => {
return str
.split('')
.reduce((acc, val) => {
if(val === char){
acc++;
};
return acc;
}, 0);
};
let count = 0;
for(let i = 0; i <= num; i++){
count += countChar(String(i), '9');
};
return count;
};
console.log(countNine(num));
ผลลัพธ์
ผลลัพธ์ในคอนโซล:
20