letecode [202] - Happy Number

 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: 

Input: 19
Output: true
Explanation: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

题目大意

   给定正整数,按照示例方式用它每个数的平方和替代它,若平方和等于1则该正整数为快乐数;若一直无限循环则非快乐数。

理  解:

   对于正整数n,n%10从后往前遍历它每一个数,n = n/10删除已遍历的数,sum表示平方和,若sum=1,则n为快乐数;否则,n = sum重新计算平方和。

  用集合set判断是否存在循环,每计算一个数,就保存在set中,若s.count(n)不等于0表明已经计算过该数,出现了循环,n为非快乐数。

代 码 C++:

class Solution {
public:
    bool isHappy(int n) {
        int sum = 0;
        
        set<int> s;
        while(n!=1){
            s.insert(n);
            while(n!=0){
                sum += (n%10)*(n%10);
                n = n/10;
            }
        
            n = sum;
            if(s.count(n)!=0)
                return false;
            sum = 0;
        }
        return true;
    }
};

运行结果:

  执行用时 :4 ms, 在所有C++提交中击败了97.12%的用户

  内存消耗 :8.5 MB, 在所有C++提交中击败了11.41%的用户
posted @ 2019-06-13 09:39  lpomeloz  阅读(100)  评论(0编辑  收藏  举报