LeetCode-Happy Number

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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值