LeetCode 202. Happy Number
原题链接在这里: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
题解:
用HashSet 存储过往的和,若是遇见了相同的和,则表示出现了无限循环,没有happy number.
Note: 1. Math.pow()的argument 和 return value 都是 double 型,返回时要注意cast.
遍历一个数字的每一位就用下面的代码:
1 while(n!=0){ 2 int digit = n%10; 3 n = n/10; 4 }
AC Java:
public class Solution { public boolean isHappy(int n) { HashSet<Integer> hs = new HashSet<Integer>(); while(!hs.contains(n)){ if(n == 1){ return true; } hs.add(n); int sum = 0; while(n != 0){ int digit = n%10; n = n/10; sum += (int)Math.pow(digit,2); } n = sum; } return false; } }
节省空间可以不需要HashSet<Integer> hs 来记录过往的digit square sum.
可以类似Linked List Cycle用快慢指针找到loop的出口, 若出来时walker 和 runner 都是1就是happy number.
AC Java:
1 class Solution { 2 public boolean isHappy(int n) { 3 if(n <= 0){ 4 return false; 5 } 6 7 int walker = n; 8 int runner = next(n); 9 while(walker != runner){ 10 walker = next(walker); 11 runner = next(next(runner)); 12 } 13 14 return runner == 1; 15 } 16 17 private int next(int n){ 18 int res = 0; 19 while(n > 0){ 20 int d = n % 10; 21 res += d * d; 22 n /= 10; 23 } 24 25 return res; 26 } 27 }