Home > Blockchain >  Count the number of occurrences of 7 in a number given by the user
Count the number of occurrences of 7 in a number given by the user

Time:10-12

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);

    }

This is what I have come up with. The output is one of the numbers has seven; if not, then zero. I want the program to count the number of times seven appears in a number.

CodePudding user response:

You can convert the number to a string, and then count how many times a character = 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)

CodePudding user response:

Following you approach you need to store the last digit to a different variable and use that for checking if it is a 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);

  • Related