Leetcode 202. Happy Number

文章作者:Tyan
博客:noahsnail.com  |  CSDN  | 

1. Description

Leetcode 202. Happy Number_第1张图片
Happy Number

2. Solution

  • Version 1
class Solution {
public:
    bool isHappy(int n) {
        int m = n;
        map sums;
        int sum = 0;
        while(sums[sum] == 0) {
            sums[sum] = 1;
            sum = 0;
            while(m) {
                int r = m % 10;
                sum += r * r;
                m = m / 10;
            }
            if(sum == 1) {
                return true;
            }
            m = sum;
        }
        return false;
    }
};
  • Version 2
class Solution {
public:
    bool isHappy(int n) {
        int slow = calDigits(n);
        int fast = calDigits(slow);
        while(slow != 1 && slow != fast) {
            slow = calDigits(slow);
            fast = calDigits(fast);
            fast = calDigits(fast);
        }
        return slow == 1;
    }
    
private:
    int calDigits(int m) {
        int sum = 0;
        while(m) {
            int r = m % 10;
            sum += r * r;
            m = m / 10;
        }
        return sum;
    }
};

Reference

  1. https://leetcode.com/problems/happy-number/description/

你可能感兴趣的:(Leetcode 202. Happy Number)