leetCode202.HappyNumber哈希

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

思路:

采用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


分享标题:leetCode202.HappyNumber哈希
网页路径:http://hxwzsj.com/article/pgpcps.html

其他资讯

Copyright © 2025 青羊区翔捷宏鑫字牌设计制作工作室(个体工商户) All Rights Reserved 蜀ICP备2025123194号-14
友情链接: 成都网站设计 成都做网站建设公司 手机网站建设套餐 温江网站设计 成都网站建设公司 手机网站制作 成都网站建设公司 高端网站设计推广 成都响应式网站建设 成都网站建设 成都商城网站制作 成都h5网站建设 移动手机网站制作 成都网站设计 企业手机网站建设 网站建设方案 成都网站建设公司 营销型网站建设 商城网站建设 成都网站制作 重庆网站制作 盐亭网站设计