小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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
Credits:
Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

分析

此题目,只要理解了快乐数的判定条件,便很简单了。

快乐数(happy number)有以下的特性:在给定的进位制下,该数字所有数位(digits)的平方和,得到的新数再次求所有数位的平方和,如此重复进行,最终结果必为1。

以十进位为例:

2 8 → 2^2+8^2=68 → 6^2+8^2=100 → 1^2+0^2+0^2=1

3 2 → 3^2+2^2=13 → 1^2+3^2=10 → 1^2+0^2=1

3 7 → 3^2+7^2=58 → 5^2+8^2=89 → 8^2+9^2=145 → 1^2+4^2+5^2=42 → 4^2+2^2=20 → 2^2+0^2=4 → 4^2=16 → 1^2+6^2=37……

因此28和32是快乐数,而在37的计算过程中,37重覆出现,继续计算的结果只会是上述数字的循环,不会出现1,因此37不是快乐数。

不是快乐数的数称为不快乐数(unhappy number),所有不快乐数的数位平方和计算,最後都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中。

因此,只要循环计算过程中,结果为该数最初值或4,则必然为不快乐数。

AC代码

class Solution {
public:
    bool isHappy(int n) {
        if (n <= 0)
            return false;

        if (n == 1)
            return true;
        int sum = n;
        while (sum != 1)
        {
            int tmp = sum;
            sum = 0;
            //求各个位平方和
            while (tmp != 0)
            {
                sum += pow(tmp % 10, 2);
                tmp /= 10;
            }//while

            if (sum == n || sum == 4)
                return false;
        }//while

        if (sum == 1)
            return true;
        else
            return false;
    }
};

GitHub测试程序源码

posted on 2015-10-09 21:08  Coding菌  阅读(151)  评论(0编辑  收藏  举报