Leetcode刷题记录[python]——258 Add Digits
生活随笔
收集整理的這篇文章主要介紹了
Leetcode刷题记录[python]——258 Add Digits
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一、前言
做這題有個小收獲,關(guān)于Digital root的解法,有個極方便的小公式:
?
二、題258 Add Digits
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
class Solution(object):def addDigits(self, num):""":type num: int:rtype: int"""if num<=9:return numelse:a=(num-1)/9if a>=0:a=int(a)else:a=int(a)-1new_num=num-9*areturn new_num然后在做后一道關(guān)于求二叉樹最大深度的問題時,參考了一些優(yōu)秀的解法得到點(diǎn)啟發(fā),寫了另一種更簡單明了的解法:
class Solution(object):def addDigits(self, num):""":type num: int:rtype: int"""if num>=10:re=num%10qu=(num-re)/10new_num=re+qureturn self.addDigits(new_num)else:return num?
轉(zhuǎn)載于:https://www.cnblogs.com/Myoungs/p/5509674.html
總結(jié)
以上是生活随笔為你收集整理的Leetcode刷题记录[python]——258 Add Digits的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java注释(转)
- 下一篇: cocos2d-x游戏引擎核心(3.x)