LeetCode202.快乐数
题目:
n
是不是快乐数。「快乐数」 定义为:1
,也可能是 无限循环 但始终变不到 1
。n
是 快乐数 就返回 true
;不是,则返回 false
。示例:
解题思路:(动规)
用unordered_set
记录每个sum
是否出现过,若出现过,则返回false
。若sum == 1
则返回true
。
版本一:Java
class Solution {
private int getSum(int n){
int res = 0;
while(n > 0){
int temp = n % 10;
res += temp * temp;
n /= 10;
}
return res;
}
public boolean isHappy(int n) {
Set<Integer> res = new HashSet<>();
while(n != 1 && !res.contains(n)){
res.add(n);
n = getSum(n);
}
return n == 1;
}
}
版本二:C++
class Solution {
public:
int getSum(int n){
int sum = 0;
while(n){
sum += (n % 10) * (n % 10);
n /= 10;
}
return sum;
}
bool isHappy(int n) {
unordered_set<int> orcured;
while(true){
int sum = getSum(n);
if(sum == 1) return true;
if(orcured.find(sum) != orcured.end()) return false;
else orcured.insert(sum);
n = sum;
}
}
};
时间复杂度:
O ( l o g n ) O(logn) O(logn)
空间复杂度:
O ( l o g n ) O(logn) O(logn)