202、快乐数

  1. 202、快乐数
    1. 示例:
  2. 题解
    1. 1、利用HashSet存储历史数字
    2. 2、数学规律
    3. 3、利用快慢指针的找出循环

202、快乐数

编写一个算法来判断一个数 n 是不是快乐数。

「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为  1,那么这个数就是快乐数。

如果 n 是快乐数就返回 True ;不是,则返回 False 。

示例:

输入:19
输出:true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

链接:https://leetcode-cn.com/problems/happy-number

题解

1、利用HashSet存储历史数字

class Solution {
    public boolean isHappy(int n) {
        Set<Integer> happySet = new HashSet<>();
        happySet.add(n);
        while(n != 1) {
            // 计算下一轮的n
            int tmp = 0;
            while(n > 0){
                tmp += (n%10)*(n%10);
                n /= 10;
            }
            // 出现循环
            if (happySet.contains(tmp)){
                return false;
            }
            // 更新n
            n = tmp;
            // 将本期结果加入到HashSet中
            happySet.add(n);
        }
        return n == 1;
    }
}

2、数学规律

class Solution {
    // 唯一的循环序列 4, 16, 37, 58, 89, 145, 42, 20
    private static Set<Integer> cycleMembers =
        new HashSet<>(Arrays.asList(4, 16, 37, 58, 89, 145, 42, 20));

    public int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            totalSum += d * d;
        }
        return totalSum;
    }


    public boolean isHappy(int n) {
        while (n != 1 && !cycleMembers.contains(n)) {
            n = getNext(n);
        }
        return n == 1;
    }
}

// 链接:https://leetcode-cn.com/problems/happy-number/solution/kuai-le-shu-by-leetcode-solution/

3、利用快慢指针的找出循环

由于快乐数是利用前一个数字求出来的,具有链表特性。

class Solution {

     public int getNext(int n) {
        int totalSum = 0;
        while (n > 0) {
            int d = n % 10;
            n = n / 10;
            totalSum += d * d;
        }
        return totalSum;
    }

    public boolean isHappy(int n) {
        int slowRunner = n;
        int fastRunner = getNext(n);
        while (fastRunner != 1 && slowRunner != fastRunner) {
            slowRunner = getNext(slowRunner);
            fastRunner = getNext(getNext(fastRunner));
        }
        return fastRunner == 1;
    }
}

// 链接:https://leetcode-cn.com/problems/happy-number/solution/kuai-le-shu-by-leetcode-solution/

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

Title:202、快乐数

Count:478

Author:攀登

Created At:2020-07-26, 00:19:44

Updated At:2024-06-15, 15:52:32

Url:http://jiafeimao-gjf.github.io/2020/07/26/202%E3%80%81%E5%BF%AB%E4%B9%90%E6%95%B0/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation