leetcode - happy number
leetcode - 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
1 class Solution { 2 public: 3 bool isHappy(int n) { 4 int hashtable[800]; 5 //vector<int> iter; 6 memset(hashtable, -1, sizeof(hashtable));//initilize all elements as -1; 7 int sum=0; 8 //int it=0; 9 10 while(hashtable[getsum(n)]== -1){ 11 sum = getsum(n); 12 hashtable[sum] = 1; 13 //if(iter.find(n)!= n.pos) return 0; 14 //iter.push_back(n); 15 16 if(sum == 1) return 1; 17 else n = sum; 18 } 19 return 0; 20 } 21 22 int getsum(int n){ 23 int nn = n; 24 int sum = 0; 25 while(nn>0){ 26 int tp = nn%10; 27 nn = nn/10; 28 sum = sum + tp*tp; 29 } 30 return sum; 31 } 32 };
好纠结。……又是hashtable……
之前想的是建一个数组,相当于对每个数有一个标志,那么数组维度应该是10^9. 但是不知道为什么对输入为1 这个case老是runtime error。难道是数组太大?
后来看了一下网上的,说是只需要9*9*9<800维数组就可以。但是其实思路和我的基本一样。不知道我的那个错在哪里……