快乐数 (Happy Number)

 

思路:可以使用快慢指针

// @Title: 快乐数 (Happy Number)
// @Author: qisiii
// @Date: 2024-09-12 20:16:57
// @Runtime: 1 ms
// @Memory: 39.8 MB
// @comment: 可以使用快慢指针
// @flag: WHITE
class Solution {
    public boolean isHappy(int n) {
        int slow=n,fast=n;
        do{
            slow=step(slow);
            fast=step(fast);
            fast=step(fast);
        }while(slow!=fast);
        return slow==1;
    }

    private int step(int n){
        int sum=0;
        while(n!=0){
            sum=sum+(n%10)*(n%10);
            n=n/10;
        }
        return sum;
    }
}

思路:递归

// @Title: 快乐数 (Happy Number)
// @Author: qisiii
// @Date: 2024-09-12 01:44:40
// @Runtime: 1 ms
// @Memory: 40 MB
// @comment: 递归
// @flag: WHITE
class Solution {
    HashSet<Integer> set=new HashSet<>();
    public boolean isHappy(int n) {
        if(n==1){
            return true;
        }
        if(set.contains(n)){
            return false;
        }else{
            set.add(n);
        }
        int sum=0;
        while(n!=0){
            sum=sum+(n%10)*(n%10);
            n=n/10;
        }
        return isHappy(sum);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18