【一天一道LeetCode】#202. Happy Number

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

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

(二)解题

题目大意:判断一个数是不是happy number。给定一个数,对其每一位上的数求平方和,得到的数一直重复球平方和,如果在这个过程中得到的平方和为1,则该数数happy number;反之则不是。

解题思路:每次对结果求每一位的平方和,判断与1相不相等。但是要考虑死循环的情况。求出来的平方和可能存在始终都不等于1,就陷入了死循环。

我们举个例子:2,一次算平方和得到:4,16,37,58,89,145,42,12,5,25,29,85,89,从这里开始循环了。

所以,我们保存下来每次算的平方和,如果算出来的平方和与前面某一个相等,就代表陷入死循环了。

考虑到这点,就可以写出如下代码:

class Solution {
public:
    bool isHappy(int n) {
        set<int> exist;
        int num = n;
        while(num!=1){//num不等于1
            int temp = num;
            int sum = 0;
            while(temp){//计算平方和
                sum+=(temp%10)*(temp%10);
                temp/=10;
            }
            if(sum==1) return true;//等于1表示是happy number
            else{//判断与之前的平方和是否有重复
                auto iter = exist.find(sum);
                if(iter!=exist.end()) break;//有重复就跳出循环
                else exist.insert(sum);//没有就加入到exist集合中
            }
            num = sum;//继续计算平方和
        }
        return num==1;//判断与1想不想等,此处排除小于等于0的数
    }
};
上一篇:Linq中Take、TakeWhile、Skip、SkipWhile的比较(转)


下一篇:Angular2 Service实践