# Easy-题目20：202. 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$1^2 + 9^2 = 82$
82+22=68$8^2 + 2^2 = 68$
62+82=100$6^2 + 8^2 = 100$
12+02+02=1$1^2 + 0^2 + 0^2 = 1$

public class Solution {
public boolean isHappy(int num) {
while(true)  {
if(num==1)
return true;
else if(num==4||num==16||num==37||num==58||num==89||num==145||num==42||num==20)
return false;
else {
int newnum=0;
while(num!=0) {
newnum=newnum+(num%10)*(num%10);
num=num/10;
}
num=newnum;
}
}
}
}

2ms，beats 85.98%，众数6ms，25.67%
Cmershen的碎碎念：
Trivial的方法是，使用一个hashset记录迭代过程中出现的数字，如果出现重复的则不是快乐数。但本算法中利用了重复数字的规律可以减少迭代次数和在hashset中的比较开销，在此第二次感叹数学的强大。

04-25 7973

11-13 1206

05-04 2849

06-03 335

08-26 6196

07-09 252

08-03 1306

05-08 1309

05-04 496

03-09 114