zoukankan      html  css  js  c++  java
  • Leetcode

    Q:

    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 = 111 + 1 = 2. Since 2 has only one digit, return it.

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

    A:

    class Solution(object):
        def addDigits(self, num):
            """
            :type num: int
            :rtype: int
            """
            num_str = str(num)
            numbers = list(num_str)
            sum_num = sum(int(t) for t in numbers)
            
            if sum_num < 10:
                return sum_num
            else:
                # print sum_num
                return self.addDigits(sum_num)

    改进以后:

    class Solution(object):
        def addDigits(self, num):
            """
            :type num: int
            :rtype: int
            """
                
            if num == 0:
                return 0
            else:
                return (num-1)%9+1
  • 相关阅读:
    表单
    html 基础代码
    thread
    流的存入读取
    异常

    Android——多线程编程练习题
    Android——进度对话框
    安卓3个练习题
    Android—对话框
  • 原文地址:https://www.cnblogs.com/ellasungenius/p/5521439.html
Copyright © 2011-2022 走看看