您的位置:首页 > 移动开发

Happy Number -- leetcode

2015-07-11 22:44 176 查看
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

算法一,

既然有死循环的可能,使用一个集合,记录已经访问过的数字。如果在集合中出现,则出现了循环。

在leetcode上用时8ms。

class Solution {
public:
    bool isHappy(int n) {
        unordered_set<int> visited;
        while (n != 1 && !visited.count(n)) {
            visited.insert(n);
            int number = 0;
            while (n) {
                number += (n % 10) * (n % 10);
                n /= 10;
            }
            n = number;
        }
        return  n == 1;
    }
};


算法二,快慢指针

使用集合到底会额外占空间。

此处使用快慢指针的概念,来探知是否存在死循环。

在leetcode上实际执行时间为4ms。

class Solution {
public:
    bool isHappy(int n) {
        int slow = n, fast = n;
        do {
            slow = next(slow);
            fast = next(next(fast));
        } while (slow != fast);
        return slow == 1;
    }
    
    int next(int n) {
        int ans = 0;
        while (n) {
            ans += (n % 10) * (n % 10);
            n /= 10;
        }
        return ans;
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: