202. Happy Number
題目原文
Example:
Input: 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1解題思路
程式解答
Last updated
Input: 19
Output: true
Explanation:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1Last updated
class Solution
{
public:
bool isHappy(int n)
{
int i = 0;
int ans = 0;
vector<int> p;
vector<int>::iterator it;
while (n)
{
i = n % 10;
ans = ans + i * i;
n /= 10;
if (!n)
{
if (ans == 1)
return true;
it = find(p.begin(), p.end(), ans);
if (it != p.end())
return false;
p.push_back(ans);
n = ans;
ans = 0;
}
}
return false;
}
};