原题链接在这里: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 throw new IllegalArgumentException("Input number is not positive."); 5 } 6 7 int walker = n; 8 int runner = n; 9 do{ 10 walker = sumOfDigitSqure(walker); 11 runner = sumOfDigitSqure(runner); 12 runner = sumOfDigitSqure(runner); 13 }while(walker != runner); 14 15 if(walker == 1){ 16 return true; 17 }else{ 18 return false; 19 } 20 } 21 22 private int sumOfDigitSqure(int n){ 23 int sum = 0; 24 25 while(n != 0){ 26 int digit = n%10; 27 n /= 10; 28 sum += digit*digit; 29 } 30 31 return sum; 32 } 33 }