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: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

 

C解法

bool isHappy(int n) {
    int lastOne = 0, nextNum = 0;
    if(n == 1)
        return true;
    else if(n == 0 || n == 2 || n == 3 || n == 4)    //之所以把4放进去是因为后来发现所有的回归都是回归到4的
        return false;
    else
    {
        while(n)
            {
                lastOne = n % 10;
                nextNum += lastOne * lastOne;
                n = n / 10;
            }
        
        return isHappy(nextNum);            //树的后遗症,一直递归
}

C++解法:

class Solution {
public:
    bool isHappy(int n) {
        int lastNum = 0, getNum = 0;
        if(n == 1)
            return true;
        else if(n == 0 || n == 2 || n == 3)
            return false;            
        else
        {
            unordered_set<int> ln;            //建立一个set来保存遇到过的值
            while(true)
            { 
                ln.insert(n);
                getNum = 0;
                while(n > 0)
                {
                    lastNum = n % 10;
                    getNum += lastNum * lastNum;
                    n /= 10;
                }
                if (getNum == 1)
                    return true;
                else if (ln.find(getNum) != ln.end())    //如果在set中发现之前出现过,说明循环了,返回0
                    return false;
                n = getNum;
            }
        }
    }
};
  • 这是一道哈希表的题;用C自己再写一个哈希表,太费力了,直接使用C++的库
  • unordered_set:就是用哈希形式建立的无序容器
posted @ 2015-10-16 09:30  dylqt  阅读(156)  评论(0编辑  收藏  举报