前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【LeetCode 202】 关关的刷题日记35 – Leetcode 202. Happy Number

【LeetCode 202】 关关的刷题日记35 – Leetcode 202. Happy Number

作者头像
WZEARW
发布2018-04-10 16:36:14
6060
发布2018-04-10 16:36:14
举报
文章被收录于专栏:专知

关关的刷题日记35 – Leetcode 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,说明这个数就是Happy Number。

思路

思路:什么时候这个数不是Happy Number呢?就是某一步得到的平方和与之前的重复了,就陷入无限循环中了,所以我们可以用set来把每一步得到的平方和存起来,进而判断该数是否是快乐的数。

代码语言:javascript
复制
class Solution {public:
    bool isHappy(int n) {
        int a,b,c;
        set<int>t;
        while(n!=1)
        {
            int sum=0;
            while(n>0)
            {
                sum+=(n%10)*(n%10);
                n/=10;
            }
            n=sum;
            if(t.find(n)!=t.end())
                return false;
            else
                t.insert(n);            
        }
        return true;
    }};

人生易老,唯有陪伴最长情,加油!

以上就是关关关于这道题的总结经验,希望大家能够理解,有什么问题可以在我们的专知公众号平台上交流或者加我们的QQ专知-人工智能交流群 426491390,也可以加入专知——Leetcode刷题交流群(请先加微信小助手weixinhao: Rancho_Fang)。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-11-14,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 专知 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 思路
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档