LeetCode - 202. 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

Code

我们先来看一个不是开心数的例子
以11为例
1^2 + 1^2 = 2
2^2 = 4
4^2 = 16
1^2 + 6^2 = 37
3^2 + 7^2 = 58
5^2 + 8^2 = 89
8^2 + 9^2 = 145
1^2 + 4^2 + 5^2 = 42
4^2 + 2^2 = 20
2^2 + 0^2 = 4

从上面的过程我们可以看到如果不是开心数,那对每位平方求和后得到的数字会出现循环的情况,即之前出现的数会再次出现。所以我们可以借助数据结构set或者map来记录每一步骤求和后的数字,在加入之前先判断是否为1,如果为1,则返回true。然后判断是否在map中已经存在,存在证明存在循环,返回false。否则把它加入到map中。

class Solution {
    public boolean isHappy(int n) {
        Map<Integer,Integer> map = new HashMap<>();
        // 如果n=1,直接返回true
        if(n == 1){
            return true;
        }
        while(n!=1) {
            int sum = 0;
            // 计算每一位的数字的平方,然后求和
            while( n!=0){
                sum += (n % 10) * (n % 10);
                n/=10;
            }
            if(sum == 1){
                return true;
            }
            if(map.containsKey(sum)){
                return false;
            }else{
                map.put(sum,1);
            }
            n = sum;
        }
        return false;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值