【Leetcode】刷题记之happy number

来源:互联网 发布:该怎么写淘宝店铺介绍 编辑:程序博客网 时间:2024/04/29 16:06

Happy Number

My Submissions
Total Accepted: 42546 Total Submissions: 124590 Difficulty: Easy

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:    bool isHappy(int n) {    unordered_map<int,bool>sum_map;//使用STL的无序图存中间生成的和,便于确定会不会进入循环    int sum=helper(n);//求digits的平方和函数    while(sum!=1)    {if (sum_map[sum]==true)        return false;    else {sum_map[sum]=true;         sum=helper(sum);}    }    return true;    }     int helper(int m)    {      int sum=0;      while(m>0)       {sum+=(m%10)*(m%10);         m=m/10;        }     return sum;    }};
注意:
1.如果出现循环,则为false。对于判断是否进入循环,可以用哈希容器unordered_map,存储已经出现过的平方和。无序图的使用详见点击打开链接
是时候复习一下数据结构了。。
2.还有一个问题,平方和,在没有引用cmath的时候,应该写成m*m,而不是m^2,这个是Matlab的语法。

anyway,keep on going!




0 0