LeetCode 202. Happy Number (快乐数字)

时间:2025-01-03 09:34:08

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

题目标签:Hash Table

  题目给了我们一个数字,让我们判断它是不是 Happy Number。

  Happy Number 最终会变成1,很好判断;Non-Happy Number 最后会无限循环在一个cycle。

  所以,我们要解决如何判断 一个数字是否在一个无限循环里,可以建立HashSet 记录它每一次的变化数字,一旦它重复了,说明,它在循环。

Java Solution:

Runtime beats 61.14%

完成日期:05/16/2017

关键词:HashSet

关键点:利用HashSet 记录每一个数字

 class Solution
{
public boolean isHappy(int n)
{
HashSet<Integer> set = new HashSet<>(); while(n != 1) // happy number will get out of this loop
{
if(set.contains(n)) // if a number repeats in a cycle, return false;
return false; set.add(n); int sum = 0; while(n != 0) // get each digit from number
{
int digit = n % 10; sum += digit * digit;
n = n / 10;
} n = sum; // update n with new number
} return true;
}
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List