0202.Happy Number
class Solution {
public:
bool isHappy(int n) {
int sum = 0;
unordered_set<int> sumSet;
while(1){
sum = 0;
while(n > 0){
int digit = n % 10;
sum += (digit * digit);
n /= 10;
}
if(sum == 1) return true;
if(sumSet.find(sum) != sumSet.end()) return false;
else sumSet.insert(sum);
n = sum;
}
return false;
}
};
class Solution {
public:
unordered_set<int> sumSet;
int getNext(int num){
int sum = 0;
while(num > 0){
int digit = num % 10;
sum += (digit * digit);
num /= 10;
}
return sum;
}
bool isHappy(int n) {
while(n != 1 && sumSet.find(n) == sumSet.end()){
sumSet.insert(n);
n = getNext(n);
}
return n == 1;
}
};
class Solution {
public:
int getNext(int num){
int sum = 0;
while(num > 0){
int digit = num % 10;
sum += (digit * digit);
num /= 10;
}
return sum;
}
bool isHappy(int n) {
int slow = n;
int fast = getNext(n);
while(fast != 1 && fast != slow){
slow = getNext(slow);
fast = getNext(getNext(fast));
}
return fast == 1;
}
};