A trick for taking apart numbers.
1234 / 10
⟹ 123.4
As you probably already know, dividing by 10 shifts the decimal place one position to the left.
Math.floor(123.4)
⟹ 123
Math.floor
does a regular division and throws away the decimal part.
Dividing by 10 with Math.floor
throws away the ones place.
1234 % 10
⟹ 4
On the other hand, the remainder when we divide by 10 is just the digit in the ones place.
while (n > 0) {
const digit = n % 10
// do something with digit
n = Math.floor(n / 10);
}
We could figure out how many digits a number has in it with some math but it’s easier to just loop, dividing by 10 at each step, until the number is 0.
Each time through the loop, the value of digit
will be the value in the ones place before we do the division.
const numNines = (n) => {
let count = 0;
while (n > 0) {
if (n % 10 === 9) {
count++
}
n = Math.floor(n / 10);
}
return count;
}
numNines(1999)
⟹ 3