zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    密码数学大作业
    《数据结构》教材测评
    机器学习概述
    SQL基础-流程控制结构
    SQL基础-变量 存储过程和函数
    SQL基础-视图
    SQL基础-TCL 事务控制语言
    SQL基础-DDL 数据定义语言
    SQL基础-DML 数据操作语言
    SQL基础 -DQL 数据查询语言(下)
  • 原文地址:https://www.cnblogs.com/immiao0319/p/8916396.html
Copyright © 2011-2022 走看看