• 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

     [暴力解法]:

    时间分析:

    空间分析:

     [优化后]:

    时间分析:

    空间分析:

    [奇葩输出条件]:

    [奇葩corner case]:

    [思维问题]:

    [一句话思路]:

    n进行 / 10等处理操作,循环条件是 n > 0

    [输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

    [画图]:

    [一刷]:

    [二刷]:

    [三刷]:

    [四刷]:

    [五刷]:

      [五分钟肉眼debug的结果]:

    [总结]:

    while (n > 0)的条件下,需要反复操作

    [复杂度]:Time complexity: O(n) Space complexity: O(n)

    [英文数据结构或算法,为什么不用别的数据结构或算法]:

    hashset重复性:加不进

    [关键模板化代码]:

    while (n > 0) {
                    remain = n % 10;
                    squareSum += remain * remain;
                    n = n / 10;
                }

    [其他解法]:

    [Follow Up]:

    [LC给出的题目变变变]:

     [代码风格] :

    class Solution {
        public boolean isHappy(int n) {
            //cc
            if (n == 0) {
                return false;
            }
            
            //ini
            int squareSum, remain;
            Set set = new HashSet();
            
            //while loop, contains
            while (set.add(n)) {
                squareSum = 0;
                
                while (n > 0) {
                    remain = n % 10;
                    squareSum += remain * remain;
                    n = n / 10;
                }
                
                if (squareSum == 1) return true;
                n = squareSum;
            }
            
            return false;
        }
    }
    View Code
  • 相关阅读:
    linux之sed用法
    个人记录-虚拟现实
    对于spark以及hadoop的几个疑问(转)
    关于老师的说的技术问题
    为什么我们总是行动不起来?你失败不是因为能力差? 如何才能实现我们的计划?
    Hibernate中一对多和多对一关系
    C# 将PDF文件转换为word格式
    C# 设置word文档页面大小
    C# 将多个office文件转换及合并为一个PDF文件
    C# 给PDF文件添加水印
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8916396.html
Copyright © 2020-2023  润新知