前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T42-快乐数

【leetcode刷题】T42-快乐数

作者头像
木又AI帮
修改2019-07-18 10:02:45
4790
修改2019-07-18 10:02:45
举报
文章被收录于专栏:木又AI帮

【英文题目】(学习英语的同时,更能理解题意哟~)

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:

代码语言:javascript
复制
Input: 
Output: true
Explanation: 
 +  = 
 +  = 
 +  = 
 +  +  = 

【中文题目】

编写一个算法来判断一个数是不是“快乐数”。

一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。

示例:

代码语言:javascript
复制
输入: 
输出: true
解释: 
 +  = 
 +  = 
 +  = 
 +  +  = 

【思路】

两个一位数的平方和的位数为一位或者两位,三个一位数的平方和为一位、两位或者三位,依次类推。由于一位数、两位数、三位数等是有限的,所以如果平方和始终不为1,那么必定循环。

用字典/map存储出现的平方和,当平方和为1,则返回true,当平方和在字典/map中出现,则返回false

【代码】

python版本

代码语言:javascript
复制
class Solution(object):
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """
        d = {}
        while n not in d:
            d[n] = 
            tmp = 
            while n > :
                tmp += (n %) ** 
                n /= 
            n = tmp
            if n == :
                return True
        return False

C++版本

代码语言:javascript
复制
class Solution {
public:
    bool isHappy(int n) {
        map <int,int> d;
        int tmp;
        while(d.find(n) == d.end()) {
            d[n] = ;
            tmp = ;
            while (n > ) {
                tmp = tmp + pow(n % , );
                n = n / ;
            }
            n = tmp;
            if (n == ) {
                return true;
            }
        }
        return false;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-04-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

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

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

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