LeetCode 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

1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1

Credits:Special thanks to @mithmatt and @ts for adding this problem and creating all test cases.

题意:
给一个数字,区分成每一位,分别平方,求和,相加,判断是否为1,如果为1则停止,否则继续判断。

思路:
每一步都很简单,稍微复杂一点的也就是,什么之后把循环停下来,停下循环的条件就是,当我们发现数字重复的时候,就可以停止循环了。

java代码:

public boolean isHappy(int n) {
        if (n == 0) return false;
        if (n == 1) return true;
        return number(n);
    }

    public boolean number(int n) {
        int count = n;
        HashSet<Integer> set = new HashSet<Integer>();
        while (set.add(count)) {
            int a = 0;
            while (count > 0) {
                int num = count % 10;
                a += num * num;
                count = count / 10;
            }
            if (a == 1) {
                return true;
            } else {
                count = a;
            }
        }
        return false;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 10,066评论 0 23
  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,789评论 0 33
  • 带着前世的乡愁 倘洋在葫芦的绿洲 那孟姜女的传说 可点缀了你的幻梦 民俗小巷的风 穿越了纺车绵绵的乐声 是谁,收藏...
    东流水sh阅读 307评论 0 4
  • 1. 两个夏天以前,青果还是别人眼里十足的坏姑娘。 吸烟、喝酒、泡吧、夜不归宿,有着与年龄不符的成熟装扮。 后来,...
    花辞MK阅读 508评论 3 5