计算用户给出的数字中出现7的次数


while (a) {
b.push(a % 10);
a = Math.floor(a / 10);
if (b == 7) {
n = n + 1;
}
console.log("<br><br>number of 7's:" + n);
}

这就是我想出来的。输出是其中一个数字有7;如果不是,则为零。我想让程序计算一个数字中出现7的次数。

您可以将数字转换为字符串,然后计算一个字符= 7的次数:

let n = 7326577
let cnt = 0;
let strN = '' + n;
for(let c of strN)
if(c == '7')
cnt ++
console.log('Number of 7's in number: ' + cnt)

按照您的方法,您需要将最后一位数字存储到另一个变量中,并使用该变量来检查它是否为7

var a = 709728457;
var b = [];
var n = 0;
while (a) {
const lastDigit = a % 10;
b.push(lastDigit); // if you still need to store all digits
a = Math.floor(a / 10);
if (lastDigit == 7) {
n = n + 1;
}
}
console.log("number of 7's:" + n);

var a = 7686774737
var no = String(a).split('').filter(e=>e==7).length;
console.log(no)

最新更新