• Leecode刷题之旅-C语言/python-202快乐数


    /*
     * @lc app=leetcode.cn id=202 lang=c
     *
     * [202] 快乐数
     *
     * https://leetcode-cn.com/problems/happy-number/description/
     *
     * algorithms
     * Easy (52.26%)
     * Total Accepted:    12.9K
     * Total Submissions: 24.7K
     * Testcase Example:  '19'
     *
     * 编写一个算法来判断一个数是不是“快乐数”。
     * 
     * 一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到
     * 1。如果可以变为 1,那么这个数就是快乐数。
     * 
     * 示例: 
     * 
     * 输入: 19
     * 输出: true
     * 解释: 
     * 1^2 + 9^2 = 82
     * 8^2 + 2^2 = 68
     * 6^2 + 8^2 = 100
     * 1^2 + 0^2 + 0^2 = 1
     * 
     * 
     */
    
    int Num(int x)
    {
        int ret=0;
        while(x){
             ret+=(x%10)*(x%10);
            x/=10;
        }
        return ret;
    }
    bool isHappy(int n) {
        if(n<=0)
            return false;
        while(n!=1){
            n=Num(n);
            if(n==4)
                return false;
        }
        return true;
    }

    这里写了一个函数,专门用来累和的。

    然后这里有个小知识,如果无限循环的话,最后结果永远都是4.

    -----------------------------------------------------------------------------------

    python:

    #
    # @lc app=leetcode.cn id=202 lang=python3
    #
    # [202] 快乐数
    #
    # https://leetcode-cn.com/problems/happy-number/description/
    #
    # algorithms
    # Easy (52.26%)
    # Total Accepted:    12.9K
    # Total Submissions: 24.7K
    # Testcase Example:  '19'
    #
    # 编写一个算法来判断一个数是不是“快乐数”。
    # 
    # 一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到
    # 1。如果可以变为 1,那么这个数就是快乐数。
    # 
    # 示例: 
    # 
    # 输入: 19
    # 输出: true
    # 解释: 
    # 1^2 + 9^2 = 82
    # 8^2 + 2^2 = 68
    # 6^2 + 8^2 = 100
    # 1^2 + 0^2 + 0^2 = 1
    # 
    # 
    #
    class Solution(object):
     def isHappy(self, n):
            # Write your code here
            if n is None:
                return False
            tmp = 0
            while tmp != 1 and tmp != 4:
                tmp = 0
                n = str(n)
                for i in n:
                    tmp += int(i) ** 2
                if tmp == 1:
                    return True
                n = tmp
            if tmp == 1:
                return True
            return False
  • 相关阅读:
    AT89C51单片机的主要组成结构
    Keil C51的库函数
    Keil C51程序设计
    bootchart 使用说明及代码分析
    [转]android下编译libusb和libhackrf
    [转]Android系统编译过程分析
    [转]Android U 盘功能实现和分析
    [转]深入理解Android之设备加密Device Encryption
    [转]Makefile 中:= ?= += =的区别
    [转]Makefile中常用的函数
  • 原文地址:https://www.cnblogs.com/lixiaoyao123/p/10529725.html
Copyright © 2020-2023  润新知