202. 快乐数 简单 哈希表判断 快慢指针 数学

  1. 快乐数
    编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」 定义为:

对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n 是 快乐数 就返回 true ;不是,则返回 false 。

示例 1:

输入:n = 19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
示例 2:

输入:n = 2
输出:false

方法一:数组模拟哈希表
class Solution {
    public boolean isHappy(int n) {
        boolean st[]=new boolean [1001];
        while(true){
            if(n==1)return true;
            n=happy(n);
            if(st[n]==true)return false;
            st[n]=true;
        }
    }
    int happy(int x){
        int s=0;
        while(x!=0){
            int t=x%10;
            x/=10;
            s+=t*t;
        }
        return s;
    }
}
方法二:快慢指针判断(弗洛伊德循环查找算法)

如果循环,快慢指针一定会相遇
慢指针速度为1,快指针速度为2

假设循环中的节点个数为n,那么这种查找法的时间和复杂度就是O(n)

class Solution {
    public boolean isHappy(int n) {
        int slow=n,fast=happy(n);
        while(true){
            if(fast==1)return true;
            if(slow==fast)return false;
            slow=happy(slow);
            fast=happy(happy(fast));
        }
    }
    int happy(int x){
        int s=0;
        while(x!=0){
            int t=x%10;
            x/=10;
            s+=t*t;
        }
        return s;
    }
}
方法三:数学 硬编码(奇技淫巧。。。)

参考:https://leetcode.cn/problems/happy-number/solution/kuai-le-shu-by-leetcode-solution/

实际上只有一个循环:44→16→37→58→89→145→42→20→4

所以幸福数的题目要么最后等于1要么最后进入这个循环,于是可以硬编码解决(在循环中判断1和4就行)

class Solution {
    public boolean isHappy(int n) {
        while(true){
            if(n==1)return true;
            if(n==4)return false;
            n=happy(n);
        }
    }
    int happy(int x){
        int s=0;
        while(x!=0){
            int t=x%10;
            x/=10;
            s+=t*t;
        }
        return s;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wow_awsl_qwq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值