美文网首页
LeetCode 202. Happy Number

LeetCode 202. Happy Number

作者: njim3 | 来源:发表于2018-11-29 09:32 被阅读1次

    题目

    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。如果该数不是“快乐数”,那么其累加的过程中中间结果必定在之前出现过,这样构成了循环,最终结果永远不会为1。
    另外,1-9的“快乐数”,经过计算只有1和7,因此最终的sum为1和7即可以判断其为“快乐数”;还有一点,2-6、8和9这些数最终都可以归结为4的累加序列(可以尝试计算一下),判断sum最终是不是4也可以得出是否为“快乐数”。
    在代码中将上述两种方法列举一下。

    代码

    // 方法1:通过判断1和7来判断是否为“快乐数”
    bool isHappy(int n) {
        int sum = 0;
        
        while (n > 0) {
            sum += pow(n % 10, 2);
            
            n /= 10;
        }
        
        if (sum >= 10)
            return isHappy(sum);
        
        if (sum == 1 || sum == 7)
            return true;
        
        return false;
    }
    
    // 方法2:通过判断sum是否为4来判断是否为“快乐数”
    bool isHappy2(int n) {
        int sum = 0;
        
        while (n > 0) {
            sum += pow(n % 10, 2);
            
            n /= 10;
        }
        
        if (sum == 4)
            return false;
        
        if (sum != 1)
            return isHappy2(sum);
        
        return true;
    }
    

    相关文章

      网友评论

          本文标题:LeetCode 202. Happy Number

          本文链接:https://www.haomeiwen.com/subject/cdlxcqtx.html