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

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1
拿到题目可以思考如下步骤:
1、拆分各位上的数,计算平方和sum
2、判断sum是否==1,是返回true,否继续拆分计算;
3、如果sum在之前已经得到,那么程序将进入死循环所以判断为false;此处可以用map判断;
代码如下:
class Solution {
public:
    bool isHappy(int n) {
        int sum=CalSquaSum(n);
        map<int,bool> m;
       while(sum!=1)
       {
           if(m[sum]==true) return false;
           m[sum]=true;
           sum=CalSquaSum(sum);
        }
        return true;
    }
        
        int CalSquaSum(int num){
            int single=0;
            int sum=0;
         while(num){
          single=num%10;
          num=num/10;
          sum+=single*single;
        }
        return sum;
        }
};


发布了30 篇原创文章 · 获赞 3 · 访问量 3万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览