【LeetCode-简单题】202. 快乐数

题目

在这里插入图片描述
这一题其实可以转变为是否存在环;
因为如果最后得到n=1的时候,再怎么继续计算也是1,说明走到了尽头才出现了环,返回true
如果最后形成环的时候不是在n=1的情况下形成的,说明存在了环,直接返回false

存在环:
在这里插入图片描述
不存在环:
在这里插入图片描述

方法一:哈希

class Solution {
    
    
    public boolean isHappy(int n) {
    
    
    Set<Integer> set = new HashSet<>();
    while( n != 1  &&  !set.contains(n)){
    
    
            set.add(n);
            n = getisHappy(n);
        }
    return n==1;
    }

    public int getisHappy(int n){
    
    
        int res = 0;
        while(n>0){
    
    
            int temp = n%10;
            res+= temp*temp;
            n = n /10;
        }
        return res;
    }
}

方法二:快慢指针

class Solution {
    
    
    public boolean isHappy(int n) {
    
    
    int slow = n;
    int fast = getisHappy(n);
    while( fast != 1  &&  slow != fast ){
    
    
           slow = getisHappy(slow);
           fast = getisHappy(getisHappy(fast));
        }
    return fast==1;
    }

    public int getisHappy(int n){
    
    
        int res = 0;
        while(n>0){
    
    
            int temp = n%10;
            res+= temp*temp;
            n = n /10;
        }
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45618869/article/details/132863160