leetcode 258. Add Digits——我擦,这种要你O(1)时间搞定的必然是观察规律,总结一个公式哇

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

For example:

Given num = 38, 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?

解法1:

复制代码
class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        # 1-9=1-9
        # 10=1
        # 11=2
        # 12=3 ...
        # 18=9
        # 19=>1
        # 20=>2
        # 21=>3
        # 99=>9
        # 100=>1
        # 101=>2
        # 999=>9
        def sum_digits(n):
            ans = 0
            while n:
                ans += n%10
                n /= 10
            return ans
            
        ans = num
        while ans > 9:
            ans = sum_digits(ans)
        return ans
        
复制代码

观察发现是一个循环数组:

复制代码
class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        # 1-9=1-9
        # 10=1
        # 11=2
        # 12=3 ...
        # 18=9
        # 19=>1
        # 20=>2
        # 21=>3
        # 99=>9
        # 100=>1
        # 101=>2
        # 999=>9
        if num == 0: return 0
        return 9 if num % 9 == 0 else num % 9
复制代码

 

 

posted @   bonelee  阅读(156)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
历史上的今天:
2017-03-14 cassandra cpp driver中bind list——用cass_statement_bind_collection函数
2017-03-14 parquet文件格式——本质上是将多个rows作为一个chunk,同一个chunk里每一个单独的column使用列存储格式,这样获取某一row数据时候不需要跨机器获取
2017-03-14 WebAssembly,可以作为任何编程语言的编译目标,使应用程序可以运行在浏览器或其它代理中——浏览器里运行其他语言的程序?
点击右上角即可分享
微信分享提示