【问题标题】:Count the number of occurrences of 7 in a number given by the user计算用户给定的数字中出现 7 的次数
【发布时间】:2021-11-30 07:53:50
【问题描述】:
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 的次数。

【问题讨论】:

  • b 有问题。在b.push(a % 10); 行中,您将其视为一个数组,然后您将if (b == 7) 视为一个数字。这是什么?
  • 最快的方法是将您的数字转换为字符串并像这样计算字符:a.toString().split('7').length - 1

标签: javascript arrays loops


【解决方案1】:
var a = 7686774737
var no = String(a).split('').filter(e=>e==7).length;
console.log(no)

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
【解决方案2】:

在您接近之后,您需要将最后一位数字存储到不同的变量中,并使用它来检查它是否是 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);

【讨论】:

    【解决方案3】:

    可以把数字转成字符串,然后算一个字符的次数=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)

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 2019-10-12
      相关资源
      最近更新 更多