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.

分析

参考:Happy number 维基百科

1. 使用set

对每一个计算的结果进行计算,如果是1则是Happy Number;不是1且在set中出现过,则不是返回false;否则将结果加入set。

2. 利用性质,特殊数字“4”

在某一时刻,出现了4的Number肯定不Happy。

1000以内的Happy Number是:

1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86, 91, 94, 97, 100, 103, 109, 129, 130, 133, 139, 167, 176, 188, 190, 192, 193, 203, 208, 219, 226, 230, 236, 239, 262, 263, 280, 291, 293, 301, 302, 310, 313, 319, 320, 326, 329, 331, 338, 356, 362, 365, 367, 368, 376, 379, 383, 386, 391, 392, 397, 404, 409, 440, 446, 464, 469, 478, 487, 490, 496, 536, 556, 563, 565, 566, 608, 617, 622, 623, 632, 635, 637, 638, 644, 649, 653, 655, 656, 665, 671, 673, 680, 683, 694, 700, 709, 716, 736, 739, 748, 761, 763, 784, 790, 793, 802, 806, 818, 820, 833, 836, 847, 860, 863, 874, 881, 888, 899, 901, 904, 907, 910, 912, 913, 921, 923, 931, 932, 937, 940, 946, 964, 970, 973, 989, 998, 1000

13和31,101和11是一样的,只是对每个数字的排列组合,那么不同序列的数字是:

1, 7, 13, 19, 23, 28, 44, 49, 68, 79, 129, 133, 139, 167, 188, 226, 236, 239, 338, 356, 367, 368, 379, 446, 469, 478, 556, 566, 888, 899

500以内的Happy Primes(质数)

7, 13, 19, 23, 31, 79, 97, 103, 109, 139, 167, 193, 239, 263, 293, 313, 331, 367, 379, 383, 397, 409, 487

代码

使用set的代码:

    public static boolean isHappy(int n) {

        if (n < 1) {
            return false;
        }

        if (n == 1) {
            return true;
        }

        Set<Integer> set = new HashSet<Integer>();
        set.add(n);

        while (true) {
            int s = 0;
            while (n > 0) {
                s += (n % 10) * (n % 10);
                n /= 10;
            }
            System.out.println(s);
            if (s == 1) {
                return true;
            } else if (set.contains(s)) {
                return false;
            }
            set.add(s);
            n = s;
        }
    }

使用特殊数字“4”的代码:

    public static boolean isHappy2(int n) {

        if (n < 1) {
            return false;
        }

        if (n == 1) {
            return true;
        } else if (n == 4) {
            return false;
        }

        int s = 0;
        while (n > 0) {
            s += (n % 10) * (n % 10);
            n /= 10;
        }

        return isHappy2(s);
    }
    原文作者:_我们的存在
    原文地址: https://blog.csdn.net/Yano_nankai/article/details/50202107
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞