资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

leetCode202.HappyNumber哈希-创新互联

202. Happy Number

专注于为中小企业提供成都网站建设、成都做网站服务,电脑端+手机端+微信端的三站合一,更高效的管理,为中小企业桥西免费做网站提供优质的服务。我们立足成都,凝聚了一批互联网行业人才,有力地推动了上1000+企业的稳健成长,帮助中小企业通过网站建设实现规模扩充和转变。

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

思路:

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

代码如下:

class Solution {
public:
    bool isHappy(int n) {
        set 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

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


文章标题:leetCode202.HappyNumber哈希-创新互联
转载来于:http://cdkjz.cn/article/eocdp.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220