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
- 1^2 + 9^2 = 82
- 8^2 + 2^2 = 68
- 6^2 + 8^2 = 100
- 1^2 + 0^2 + 0^2 = 1
如果迭代到最后为1了,就返回true
C++(0ms):
1 class Solution { 2 public: 3 int fun(int n){ 4 int res = 0 ; 5 while(n){ 6 res += pow(n%10 , 2) ; 7 n /= 10 ; 8 } 9 return res ; 10 } 11 12 bool isHappy(int n) { 13 bool flag[1000] = {0} ; 14 n = fun(n) ; 15 while(!flag[n]){ 16 flag[n] = true ; 17 if (n == 1) 18 return true ; 19 n = fun(n) ; 20 } 21 return false ; 22 } 23 };