LeetCode 202. 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
题目标签:Hash Table
题目给了我们一个数字,让我们判断它是不是 Happy Number。
Happy Number 最终会变成1,很好判断;Non-Happy Number 最后会无限循环在一个cycle。
所以,我们要解决如何判断 一个数字是否在一个无限循环里,可以建立HashSet 记录它每一次的变化数字,一旦它重复了,说明,它在循环。
Java Solution:
Runtime beats 61.14%
完成日期:05/16/2017
关键词:HashSet
关键点:利用HashSet 记录每一个数字
1 class Solution 2 { 3 public boolean isHappy(int n) 4 { 5 HashSet<Integer> set = new HashSet<>(); 6 7 while(n != 1) // happy number will get out of this loop 8 { 9 if(set.contains(n)) // if a number repeats in a cycle, return false; 10 return false; 11 12 set.add(n); 13 14 int sum = 0; 15 16 while(n != 0) // get each digit from number 17 { 18 int digit = n % 10; 19 20 sum += digit * digit; 21 n = n / 10; 22 } 23 24 n = sum; // update n with new number 25 } 26 27 return true; 28 } 29 }
参考资料:N/A
LeetCode 题目列表 - LeetCode Questions List