202. 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
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

Solution:Hashset

思路: 看结果是否开始重复,或达到1
Time Complexity: .. Space Complexity: ..

Solution Code:

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> inLoop = new HashSet<Integer>();
        
        while (inLoop.add(n)) {
            int squareSum = 0;
            while (n > 0) {
                int digit = n % 10;
                squareSum += digit * digit;
                n /= 10;
            }
            if (squareSum == 1)
                return true;
            else
                n = squareSum;

        }
        return false;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 雾山一叶多秋梦,未至天明空思人。 大意:在雾山之上连那一片叶子都在频繁的做着向往秋天的梦,我却因为思念故人而等不到天亮。
    北暮无泪阅读 262评论 0 1
  • 网络上流行一句话:你丑,你先睡。 就拿肌肉君来说,不能说活的十分健康,但尽量每天都自己做饭,每周至少保持四次健身频...
    灵哩女阅读 524评论 0 3
  • 我之前工作的机构是一个教孩子学习和金钱建立关系的机构。当然,说的更加朴素点就是,每个人都能谈点什么并且还谈的不一样...
    WEI_曹蕾阅读 215评论 0 0
  • 妹妹有个朋友,比她小两岁。妹妹比我小了三岁。 她常常来家里玩,我也时常可以见到她。她叫我黛姐,语气自然,仿佛这就是...
    默默轻寒阅读 10,158评论 0 0