题目:
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
- 1^2 + 9^2 = 82
- 8^2 + 2^2 = 68
- 6^2 + 8^2 = 100
- 1^2 + 0^2 + 0^2 = 1
链接:
https://leetcode.com/problems/happy-number/
答案:
暴力解决,直接给每个数的每位计算平方和就行,然后把中间的数都记录下来,如果下次出现这个数,就是loop了。
代码:
#include<vector> using std::vector; class Solution {
private:
vector<int> med; bool inMed(int n)
{
vector<int>::iterator beg;
for(beg = med.begin(); beg != med.end(); ++ beg)
{
if(*beg == n)
{
return true;
}
} return false;
} int sum(int n)
{
int s = ;
while(n != )
{
int modn = n % ;
s += modn * modn;
n = n /;
} return s;
} public:
bool isHappy(int n)
{
if(n == || n == || n == || n == )
{
return true;
} med.clear();
med.push_back(n); int result = n;
bool isLoop = false;
while( result != )
{
result = sum(result);
if(result != && inMed(result))
{
isLoop = true;
break;
} med.push_back(result);
} return !isLoop;
}
};
代码中的isHappy()方法的最开头我是随便加了几个判断,哈哈,题目中给出的快乐数应该会在后台的测试数据中。