您的位置:首页 > 移动开发

leetcode happy number

2015-11-19 17:40 239 查看
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

12 + 92 = 82

82 + 22 = 68

62 + 82 = 100

12 + 02 + 02 = 1

有一些题一看我就觉得有些难,这就是一道。首先,我很不喜欢题目里定义了很多东西这样。于是乎,刚开始的思路就华丽丽地跑偏了,走到了总结规律上面。

是的,没错,我首先想到的就是有什么规律,什么规律会是一个happy number。。想了很多甚至连(a+b)2=a2+b2+2ab呀这种公式都试啊试的

后来就想着算了,按照这个走吧。

问题一:提取每一位,刚开始都忘记了怎么提取每一位。不过后来想到了。

问题二:怎样就判断不是happy number了,这也是一个卡住我的地方,我最开始想的是假如回到原点就不是happy number了,就是2计算了一堆最后又回到2,2显然不是happy number。

但是,没错,超时了。后来看了陆草纯的代码,其他搜了很多都是用set实现的,我明显更加喜欢map,陆草纯用map记录了哪些数字已经被计算过但是不是happy number的。这其实是一个循环。例如

2->4->16->37->58->89->145->20->2->4...开始循环,所以这个循环里的每个数都会进入一个圈圈。我们用map记录哪些已经被计算过,如果已经被计算过,我们又遇到它且它不为1,直接false说明我们进入一个循环。

因为一个happy number的数列里一定是只出现一次的。

class Solution {
public:
int GetSum(int n){
int c=0,sum=0;
while(n!=0){
c=n%10;
n/=10;
sum+=(c*c);
}
return sum;
}

bool isHappy(int n) {
if(n==1) return true;
unordered_map<int,bool> haveCalIt;
int sum=GetSum(n);
while(sum!=1){
if(haveCalIt[sum]==true) return false;
haveCalIt[sum]=true;
sum=GetSum(sum);

}
return true;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: