LeetCode-Happy Number

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

Description:
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:

Input: 19
Output: true

Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

题意:判断一个正数是否是个“Happy Number”。定义是将这个数的每一位上的数平方求和重新赋给这个数,直到这个数的值为1或者产生一个循环停止;

解法:解决这道题目的关键是如何判断终止条件,有两种情况我们会退出循环;第一种就是判断平方后的值为1即可;第二种我们需要判断是否产生了一个循环,可以将每次求得的平方和存储在哈希表中,这样,只要我们检测到哈希表中已经存在这个数了,那么说明已经产生了循环,就可以退出循环了;

Java
class Solution {
    public boolean isHappy(int n) {
        Set<Integer> table = new HashSet<>();
        while (!(n == 1 || table.contains(n))) {
            int key = n;
            n = getNextNum(n);
            table.add(key);
        }
        return n == 1 ? true : false;
    }

    private int getNextNum(int n) {
        int sum = 0;
        while (n > 0) {
            sum += Math.pow(n % 10, 2);
            n /= 10;
        }
        return sum;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/82735654
今日推荐