const getNum = (first: number, last: number) => {
let num: number = 0;
for (let i = first; i <= last; i++) {
if (i === 1) {
num++;
} else if (parseInt(i / 10) === 1) {
num++;
} else if (i % 10 === 1) {
num++;
} else if (parseInt(i / 100) === 1) {
num++;
} else if (parseInt(i/ 10) % 10 === 1) {
num++;
}
}
return num;
};
console.log(getNum(1, 21), 888888); 此解法有问题
正确解法
const getNum = (first: number, last: number) => {
let str = '';
for (let i = first; i <= last; i++) {
str += i;
}
const n = str.match(/1/g);
return n?.length;
};
console.log(getNum(1, 99));