资讯专栏INFORMATION COLUMN

[Leetcode] Happy Number 快乐数

lindroid / 1997人阅读

摘要:集合法复杂度时间待定空间待定思路根据快乐数的计算方法,我们很难在有限步骤内确定一个数是否是快乐数,但使用排除法的话,我们可以尝试确定一个数不是快乐数。根据题意,当计算出现无限循环的时候就不是快乐数。

Happy Number

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
集合法 复杂度

时间 待定 空间 待定

思路

根据快乐数的计算方法,我们很难在有限步骤内确定一个数是否是快乐数,但使用排除法的话,我们可以尝试确定一个数不是快乐数。根据题意,当计算出现无限循环的时候就不是快乐数。出现无限循环的说明产生了相同的结果,而判断相同结果只要用Set就行了。

代码
public class Solution {
    public boolean isHappy(int n) {
        Set set = new HashSet();
        while(n!=1){
            int sum = 0;
            while(n>0){
                sum += (n % 10) * (n % 10);
                n = n / 10;
            }
            if(set.contains(sum)){
                return false;
            } else {
                set.add(sum);
            }
            n = sum;
        }
        return true;
    }
}
后续 Follow Up

Q: 可不可以不用HashTable或者HashSet解决这题?
A: 可以,参考Linked List Cycle,我们可以记录下每轮产生的结果,同时用快慢指针遍历,一旦快慢指针相与便说明有环。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66163.html

相关文章

  • LeetCode 攻略 - 2019 年 7 月上半月汇总(55 题攻略)

    摘要:微信公众号记录截图记录截图目前关于这块算法与数据结构的安排前。已攻略返回目录目前已攻略篇文章。会根据题解以及留言内容,进行补充,并添加上提供题解的小伙伴的昵称和地址。本许可协议授权之外的使用权限可以从处获得。 Create by jsliang on 2019-07-15 11:54:45 Recently revised in 2019-07-15 15:25:25 一 目录 不...

    warmcheng 评论0 收藏0
  • LeetCode 攻略 - 2019 年 7 月下半月汇总(100 题攻略)

    摘要:月下半旬攻略道题,目前已攻略题。目前简单难度攻略已经到题,所以后面会调整自己,在刷算法与数据结构的同时,攻略中等难度的题目。 Create by jsliang on 2019-07-30 16:15:37 Recently revised in 2019-07-30 17:04:20 7 月下半旬攻略 45 道题,目前已攻略 100 题。 一 目录 不折腾的前端,和咸鱼有什么区别...

    tain335 评论0 收藏0
  • 前端 | 每天一个 LeetCode

    摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...

    张汉庆 评论0 收藏0
  • [LeetCode/LintCode] Happy Number

    Problem Write an algorithm to determine if a number is happy.A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squar...

    崔晓明 评论0 收藏0
  • leetcode刷题笔记(2)(python)

    摘要:思路先用将字符串分割,再遍历,将字符串内每个单词进行翻转代码题意给定一个字符串,将字符串按照翻转,不翻转的规则进行处理。思路先将字符串分段,然后再根据段落进行处理最后将字符串输出。 344 Reverse String题意:给出一个字符串对字符串进行翻转(reverse)思路:直接使用切片函数进行翻转(网上看到的,具体怎么使用有点迷)[::-1]代码:`class Solution(...

    Guakin_Huang 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<