LeetCode 202. Happy Number(快乐数字)

来源:互联网 发布:加权平均图像融合算法 编辑:程序博客网 时间:2024/06/05 15:18

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

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: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

方法一:使用哈希集合检测是否重复(环路)。

public class Solution {    public boolean isHappy(int n) {        Set<Integer> set = new HashSet<>();        while (true) {            if (n == 1) return true;            if (set.contains(n)) return false;            set.add(n);            int next = 0;            while (n>0) {                int digit = n % 10;                n /= 10;                next += digit * digit;            }            n = next;        }    }}

方法二:使用快慢指针检测环路。

public class Solution {    private int calc(int n) {        int next = 0;        while (n>0) {            int digit = n % 10;            n /= 10;            next += digit * digit;        }        return next;    }    public boolean isHappy(int n) {        int slow = n;        int fast = n;        while (true) {            slow = calc(slow);            fast = calc(calc(fast));            if (fast == 1) return true;            if (slow == fast) return false;        }    }}


0 0