旋转数字问题-为什么采用n mod 10和n/10



我试图在一个名为Rotate digits的leet代码上解决这个问题。

这是Javascript中问题的工作解决方案:

var IsGood = function(n){
let result = false;

while(n > 0){
let digit = n % 10;  // 2 % 10
// ignore 0, 1, 8; by themselves, no change
if( (digit === 3) || (digit === 4) || (digit === 7) ) return false;
if( (digit === 2) || (digit === 5) || (digit === 6) || (digit === 9) ) result = true;
n /= 10;
}
return result;
}
var rotatedDigits = function(N) {
let count = 0;
for(let i = 1; i <= N; i++){
if(IsGood(i)) count++;
}
return count;
}

我在IsGood函数中的问题是,为什么我们取n%10,然后除以n/=10。我在这个问题的几乎所有解决方案中都看到了这种实现。有人能解释一下这背后的逻辑吗?

取123

该数字除以10后的余数为3(123%10(=3。

所以n%10会给你数字的最后一位

如果你想测试数字中的下一个数字,你必须去掉3。这样做的方法是除以10,只取整数部分(12.3减去.3部分(,你得到的是123/10

你可以一直这样做,直到你得到一个小于10的数字,这个数字必须是最后一个数字!该算法是一种使用数学而不是字符串操作来检查数字中每个数字的方法

123 % 10 = 3 first digit
123 / 10 = 12
12 % 10 = 2 next digit
12 /  10 = 1

1<10所以最后一位

最新更新