202. Happy Number
problem description
Input: 19
Output: true
Explanation:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1algorithm thought
code
algorithm analysis
Last updated
Input: 19
Output: true
Explanation:
1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1Last updated
class Solution {
public:
bool isHappy(int n) {
int fast=n;
int slow=n;
while(1){
fast=happy(happy(fast));
slow=happy(slow);
if(fast==1)
return true;
if(fast==slow)
return false;
}
return false;
}
int happy(int a){
int res=0;
while(a){
res+=(a%10)*(a%10);
a=a/10;
}
return res;
}
};