1

I am trying to write a block of code which will separate digits (with modulus operator) in a number first and count how many digit "6" are there in the number.

I tried so many things but I think I have logic problem with the way I think.

output = [];

var count = 0;


while (a > 0){
  output.push(a % 10);
  a = Math.floor(a/10);
  if(a == 6){
      count++;
    }
}

When I run this code on Safari, It shows the entered number as it is, but it shows "0" for the variable count.

3
  • 1
    Convert to a string and find the "6"es? Commented Oct 23, 2019 at 0:13
  • Since this is a homework, I am not allowed to convert the number to a string. Commented Oct 23, 2019 at 0:15
  • 1
    var chars = a+"".split(''); should return a array of chars which you can now count by a simple for next loop. Commented Oct 23, 2019 at 0:18

2 Answers 2

3

Math.floor(a/10) doesn't give the current digit. a % 10 gives the current digit.

You have check if the current digit a % 10 is 6.

Live Example:

let output = [];
let count = 0;
let a = 1667;

while (a > 0) {
  let digit = a % 10;
  output.push(digit);
 
  if (digit == 6) {
    count++;
  }
    
  a = Math.floor(a / 10);
}

console.log(count);

Sign up to request clarification or add additional context in comments.

Comments

1

You know the last digit, so you can subtract it and divide with 10, instead of using Math.floor.

let number = 1626364656; // has 5 sixes
let sixesCount = 0;
while (number > 0) {
    const digit = number % 10;
    if (digit === 6) {
        sixesCount++;
    }
    number = (number - digit) / 10;
}
console.log('Found', sixesCount, 'sixes.'); // "Found 5 sixes."

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.