leetcode (Happy Number)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85275909

Title:Happy Number    202

Difficulty:Easy

原题leetcode地址:   https://leetcode.com/problems/happy-number/

1.  见代码注释

时间复杂度:O(n),一次一层for循环。

空间复杂度:O(n),申请Set空间。

    /**
     * 如果最后不为1,最后会收敛某个数,用Set的唯一性存放这个数
     * @param n
     * @return
     */
    public static boolean isHappy(int n) {

        if (n < 1) {
            return false;
        }

        Set<Integer> set = new HashSet<>();

        while (n != 0 && !set.contains(n)) {
            set.add(n);

            String s = n + "";
            char nums[] = s.toCharArray();

            int total = 0;
            for (int num : nums) {
                int i = num - 48;
                total += i * i;
            }

            n = total;

        }

        return n == 1;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85275909