题目:
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
链接: http://leetcode.com/problemset/algorithms/
2/23/2017, Java
注意HashSet的API, performance并不好
1 public class Solution { 2 public boolean isHappy(int n) { 3 if (n == 0) return false; 4 HashSet<Integer> s = new HashSet<Integer>(); 5 int val = 0, tmp; 6 7 while (val != 1 && !s.contains(val)) { 8 s.add(val); 9 val = 0; 10 while (n > 0) { 11 tmp = n % 10; 12 val += tmp * tmp; 13 n /= 10; 14 } 15 n = val; 16 } 17 18 if (val == 1) return true; 19 return false; 20 21 } 22 }
别人的算法
更好的解可以把Space Complexity 简化到 O(1),使用 fast / slow pointer进行Cycle Detection的思路,很巧妙。 更奇妙的是运行时间也减少了。
留给二刷