当前位置: 代码迷 >> 综合 >> Leetcode 202. Happy Number (cpp)
  详细解决方案

Leetcode 202. Happy Number (cpp)

热度:24   发布时间:2023-11-26 06:05:08.0

题目

在这里插入图片描述

解法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;}
};
  相关解决方案