标签:
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.
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 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5662234.html