题目
解法1:hashtable
建立一个hashtable,检查是否会在循环过程中出现已经出现的数字
class Solution {
public:bool isHappy(int n) {
unordered_map<int ,int> seen;while(n != 1 && seen.find(n) == seen.end()){
seen[n] = 1;n = getNext(n);}return n == 1;}int getNext(int num){
int res = 0;int div, mod;while(num){
mod = num % 10;num = num / 10;res += mod * mod;}return res;}
};
解法2:Floyd’s Cycle
参考成环检测的快慢指针方法Leetcode 141:Linked List Cycle
class Solution {
public:bool isHappy(int n) {
int slow = n;int fast = getNext(n);while(fast != 1 && slow != fast){
slow = getNext(slow);fast = getNext(getNext(fast));}return fast == 1;}int getNext(int num){
int res = 0;int div, mod;while(num){
mod = num % 10;num = num / 10;res += mod * mod;}return res;}
};