zoukankan      html  css  js  c++  java
  • Python3解leetcode Binary Tree PathsAdd Digits

    问题描述:

    Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

    Example:

    Input: 38
    Output: 2 
    Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2. 
                 Since 2 has only one digit, return it.
    

    Follow up:
    Could you do it without any loop/recursion in O(1) runtime?

    思路:

    最暴力的思路是用循环,但是最后题目提示可以不用循环,以及运行时间O(1).

    那么我们先来观察1到20的所有的结果:

    1    1
    2    2
    3    3
    4    4
    5    5
    6    6
    7    7
    8    8    
    9    9    
    10    1
    11    2
    12    3    
    13    4
    14    5
    15    6
    16    7
    17    8
    18    9
    19    1
    20    2

    根据上面的列举,我们可以得出规律,每9个一循环,所有大于9的数的结果都是对9取余,其中9的倍数 对9取余就是0了,此时返回9;若非9的倍数,则返回余数。这里有个特殊情况,就是0, 0对9取余,得到的0,但是返回值却应该是0,所以这个需要特殊处理下。

    代码:

    1 class Solution:
    2     def addDigits(self, num: int) -> int:
    3         return 9 if num != 0 and num % 9 == 0 else num % 9
  • 相关阅读:
    POJ3613 Cow Relays 经过n条边的最短路
    UML笔记(六)
    UML主要内容及参考资料
    UML笔记(五)
    UML笔记(一)
    UML笔记(三)
    UML笔记(四)
    软件工程——第十一章 软件项目管理
    软件工程——第十章 软件工程管理
    UML笔记(二)
  • 原文地址:https://www.cnblogs.com/xiaohua92/p/11195015.html
Copyright © 2011-2022 走看看