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
算法一,
既然有死循环的可能,使用一个集合,记录已经访问过的数字。如果在集合中出现,则出现了循环。
在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;
}
};版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/elton_xiao/article/details/46845563