happy num

来源:互联网 发布:bat转换成exe 知乎 编辑:程序博客网 时间:2024/05/29 15:05

例如

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
两种方法,迭代和while

计算出现重复,则不是

class Solution {

public:
    unordered_map<int ,int >result;
    bool isHappy(int n) {
   /*
      if (n==1)
{
return true;
}
else{
unordered_map<int ,int>result_count;
int t=0;
++result_count[1];
while(1){

    while(n)
{
t=t+(n%10)*(n%10);
         n=n/10;
}
if(t==1)
return true;


if(result_count.find(t)!=result_count.end())
{
return false;
}


++result_count[t];
n=t;
t=0;
}
}
*/
if(n==1)
return true;
int t=0;
while(n)
{
t=t+(n%10)*(n%10);
        n=n/10;
}
if(result.empty())
{
result[1]++;
}
else
{
if(t==1)
return true;
if(result.find(t)!=result.end())
{
return false;
}
}
++result[t];
return isHappy(t);
    }
};
0 0
原创粉丝点击