前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode202 Happy Number

LeetCode202 Happy Number

作者头像
用户1665735
发布2019-02-19 12:40:57
4070
发布2019-02-19 12:40:57
举报
文章被收录于专栏:kevindroidkevindroid

题目

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. 快乐数的具体解释参考这里

解题思路

由上文的资料可得,不是快乐数的数称为不快乐数(unhappy number),所有不快乐数的数位平方和计算,最後都会进入 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 的循环中。 那么,可以用hashset保存这些值,遇到直接返回false即可。

代码语言:javascript
复制
public boolean isHappy(int n) {
        if (n == 0) return false;
        if (n == 1) return true;
        int sum = 0;
        HashSet<Integer> set = new HashSet<>();
        set.add(4);
        set.add(16);
        set.add(37);
        set.add(58);
        set.add(89);
        set.add(145);
        set.add(42);
        set.add(20);
        while (n != 0) {
            sum += (n % 10) * (n % 10);
            n /= 10;
        }
        return !set.contains(sum) && isHappy(sum);
    }
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年02月20日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 解题思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档