leetCode 202. Happy Number 哈希

发布时间:2020-03-31 02:02:25 作者:313119992
来源:网络 阅读:804

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

思路:

采用set来判断容器中是否有该元素出现过,如果出现过,那么就形成了环状,结果返回false。否则找到快乐数字。返回true。

代码如下:

class Solution {
public:
    bool isHappy(int n) {
        set<int > myset;
        int total = 0;
        while(n != 1)
        {
            while(n)
            {
                total += (n%10)*(n%10);
                n /= 10;
            }
            if(total == 1)
                return true;
            if(myset.find(total) != myset.end())
                return false;
            else
                myset.insert(total);
            n = total;
            total = 0;
        }
        return true;
    }
};

关于set容器的使用练习。

2016-08-13 13:49:32

推荐阅读:
  1. 136. Single Number leetcode做题报告
  2. leetCode 349. Intersection of Two Arrays 哈希

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

table hash pp

上一篇:Open-falcon原理介绍

下一篇:"Base SDK Missing"问题的解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》