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
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 =1
分析:
这题的关键是如何退出循环如果那个数不是hapy number. 这里用了一个方法,就是用hashset保存得到过的数,如果出现重复,那就不是Happy number.
1 public class Solution { 2 /** 3 * @param n an integer 4 * @return true if this is a happy number or false 5 */ 6 public boolean isHappy(int n) { 7 if (n < 1) return false; 8 9 Set<Integer> hashSet = new HashSet<Integer>(); 10 hashSet.add(n); 11 12 while (n != 1) { 13 n = getNewNumber(n); 14 if (hashSet.contains(n)) { 15 return false; 16 } 17 hashSet.add(n); 18 } 19 return true; 20 } 21 22 public int getNewNumber(int n) { 23 int total = 0; 24 while (n != 0) { 25 total += (n % 10) * (n % 10); 26 n = n / 10; 27 } 28 return total; 29 } 30 }
1 public class Solution { 2 int digitSquareSum(int n) { 3 int sum = 0, tmp; 4 while (n > 0) { 5 tmp = n % 10; 6 sum += tmp * tmp; 7 n /= 10; 8 } 9 return sum; 10 } 11 12 boolean isHappy(int n) { 13 int slow, fast; 14 slow = fast = n; 15 do { 16 slow = digitSquareSum(slow); 17 fast = digitSquareSum(fast); 18 fast = digitSquareSum(fast); 19 } while(slow != fast); 20 if (slow == 1) return true; 21 return false; 22 } 23 }