【leetcode】Happy Number

来源:互联网 发布:淘宝的大刀和鑫鑫 编辑:程序博客网 时间:2024/06/09 18:37

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的时候,输出为happy number,否则继续计算,直到和的值出现循环。因此,不能用递归的方法。用result的数组来记录每次的和,如果出现一样的,就认为出现了循环。开始的时候尝试用vector来做,但是out of memory,不知道什么情况。

因此我用数组来存储sum,根据平方和的范围进行估计一下,int型数的范围32位下上限是4294967296,也就是10位,9*9*10的话也才810,开一个1000的数组就可以完成这个工作。
【看了下网上的答案,用hush table 和unsortorder_map做的也比较多,我需要好好学习~~】

class Solution {public:    bool isHappy(int n) {      if(n==1) return true;      if(n==0) return false;      int result[1000];      memset(result,0,1000);      result[0]=n;      int i=0;      while(1)      {          int temp=result[i];          int answer=0;          while(temp/10)          {              answer=answer+(temp%10)*(temp%10);              temp=temp/10;          }          answer=answer+(temp%10)*(temp%10);          if(answer==1)            return true;          else          {              for(int j=0;j<i+1;j++)              {                  if(answer==result[j])                    return false;              }                      i++;              result[i]=answer;          }      }    }};
0 0