js 代码面试题
~~~ 统计 1-n 中 1出现的次数。
方法一, 转换成字符串,然后通过正则匹配1, 累加次数【或者转换成字符串,在转换成数组,过滤出 1出现的值 !】
js:
function findOne(n) {
Array.from({length: n})
.map((v, i) => i+1)
.reduce((pre, cur) =>{
const OneCount = String(cur).match(/1/g).?length || 0;
or
const OneCount1 = String(cur).split('').filter(v => v === '1').length;
return pre + OneCount
}, 0)
}
method2: 数学方法:将传入的 n 分为 高低位。
function findOne2(n, x) {
let factor = 1;
let count = 0;
let next = parseInt(n / factor);
while (next ! == 0) {
let lower = n - next * factor;
let cur = n % 10;
let high = n / (factor * 10);
if (cur > x) {
count += (high + 1) * factor;
}else if( cur === x) {
count += (high * factor + lower + 1);
}else {
count += high * factor;
}
factor *= 10;
next = parseInt(n / factor)
}
return count
}