[leetcode]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,重复之前步骤,若始终得不到1,则不是快乐数。取一个非快乐数计算发现,循环的过程中都会出现4,所以依次求各个位上的数字平方和,不为1并且循环的数字不为4,更新,并继续求平方和。

class Solution {
public:
    bool isHappy(int n) {
        int cur_sum = square(n);
        while(cur_sum!=1 && cur_sum!=4)
        {
            cur_sum = square(cur_sum);
        }
        if(cur_sum == 1)
            return true;
        else
            return false;                               
    }  
         int square(int n)
        {
        int m = 0;
        int sum = 0;
        while(n)
        {
            m = n % 10;
            sum += m*m;
            n /= 10;
        }
             return sum;
        }
};

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/84890050