1. 程式人生 > >經典演算法題之Happy Number

經典演算法題之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

class Solution {
public:
     intgetWeishu(int n) {
          int weishu=0;
          for(int i=1; i<=n; i*=10, ++weishu) {
              ;
          }
          return weishu;
     }
     voidgetAllDigit(const int n, vector<int> &digits){
          int weishu=getWeishu(n);
          int number=n;
          for(int i=weishu, l=10; i>0; --i) {
              int d;
              d=number%l;
              digits.push_back(d);
              number/=l;
          }
     }
     intgetDigitSum(vector<int> digits) {
          int sum=0;
          for(vector<int>::iterator it=digits.begin();
          it!=digits.end(); ++it) {
              sum+=(*it)*(*it);
          }
          return sum;
     }
     vector<int>caculated;
   bool isHappy(int n) {
       vector<int> digits;
          getAllDigit(n, digits);
          int sum=getDigitSum(digits);
          if( sum== 1){
              return true;
          }
          else {
              for(vector<int>::iterator it=caculated.begin();
              it!=caculated.end(); ++it) {
                   if(*it == sum)
                        return false;
              }
              caculated.push_back(sum);
              return isHappy(sum);
          }
          return false;
   }
};

上述演算法超時。

改進:

用雜湊map對映。也可以用一個大於729的陣列代替map,因為9位數的乘積之和最大為9×9×9=729.

class Solution {
public:

int getDigitSum(int n) {
int sum=0;
while(n) {
    int t=n%10;
    sum+=t*t;
    n/=10;
}
return sum;
}
map<int, bool> m;
    bool isHappy(int n) {
int sum=getDigitSum(n);

if( sum== 1){
return true;
}
else {
if(m[sum] == true) {
    return false;
}
m[sum]=true;
return isHappy(sum);
}
    }
};