更多题解尽在 https://sugar.matrixlab.dev/algorithm 每日更新。
组队打卡,更多解法等你一起来参与哦!
暴力
解题思路:暴力,根据题意模拟。需要注意的地方是 n
在
1
≤
n
≤
9
1 \leq n \leq 9
1≤n≤9 时, n
是否是快乐数。
Code
class Solution {
public boolean isHappy(int n) {
while (true) {
int result = 0;
while (n > 0) {
result += (int) Math.pow(n % 10, 2);
n /= 10;
if (n == 0 ) {
if (result == 1 || result == 7) {
return true;
} else if (result > 1 && result < 10) {
return false;
} else {
n = result;
result = 0;
}
}
}
}
}
}