【宫水三叶】简单模拟题
模拟
利用 $n$ 的范围为 $1e4$,我们可以直接检查 $[1, n]$ 的每个数。
由于每一个位数都需要翻转,因此如果当前枚举到的数值 x 中包含非有效翻转数字(非 0125689)则必然不是好数;而在每一位均为有效数字的前提下,若当前枚举到的数值 x 中包含翻转后能够发生数值上变化的数值(2569),则为好数。
代码:
###Java
class Solution {
public int rotatedDigits(int n) {
int ans = 0;
out:for (int i = 1; i <= n; i++) {
boolean ok = false;
int x = i;
while (x != 0) {
int t = x % 10;
x /= 10;
if (t == 2 || t == 5 || t == 6 || t == 9) ok = true;
else if (t != 0 && t != 1 && t != 8) continue out;
}
if (ok) ans++;
}
return ans;
}
}
###TypeScript
function rotatedDigits(n: number): number {
let ans = 0
out:for (let i = 1; i <= n; i++) {
let ok = false
let x = i
while (x != 0) {
const t = x % 10
x = Math.floor(x / 10)
if (t == 2 || t == 5 || t == 6 || t == 9) ok = true
else if (t != 0 && t != 1 && t != 8) continue out
}
if (ok) ans++
}
return ans
};
###Python3
class Solution:
def rotatedDigits(self, n: int) -> int:
ans = 0
for i in range(1, n + 1):
ok, x = False, i
while x != 0:
t = x % 10
x = x // 10
if t == 2 or t == 5 or t == 6 or t == 9:
ok = True
elif t != 0 and t != 1 and t != 8:
ok = False
break
ans = ans + 1 if ok else ans
return ans
- 时间复杂度:共有 $n$ 个数需要枚举,检查一个数需要遍历其每个数字,复杂度为 $O(\log{n})$。整体复杂度为 $O(n\log{n})$
- 空间复杂度:$O(1)$
最后
如果有帮助到你,请给题解点个赞和收藏,让更多的人看到 ~ ("▔□▔)/
也欢迎你 关注我 和 加入我们的「组队打卡」小群 ,提供写「证明」&「思路」的高质量题解。
所有题解已经加入 刷题指南,欢迎 star 哦 ~