2023年4月26日 星期三

4/26每日一題

 Given an integer num, repeatedly add all its digits until the result has only one digit, and return it.

 

Example 1:

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

Example 2:

Input: num = 0
Output: 0

 

Constraints:

  • 0 <= num <= 231 - 1

 

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

------------------------------------------------------------------------------------------------------

class Solution(object):
    def addDigits(self, num):
        """
        :type num: int
        :rtype: int
        """
        '''判斷是否是1位數,如果是就返回num'''
        if len(str(num)) == 1:

            return num
        else:
           '''如果非1位數,將各位數加總,返回到num再次判斷是否為1位數'''
           while len(str(num)) >1 :
                str_num=str(num)
                lis_num=list(str_num)
                tol = sum(map(int,lis_num))
                #map(func,iterable)
                '''func是用來對可迭代的函數進行處理
                這邊將list中每個元素轉成int後進行加總
                '''
                num = tol
                #重新賦予num新的值,再次進入while判斷是否為一位數
               
        return num
               
           
           

s=Solution()
print(s.addDigits(38))
print(s.addDigits(0))
print(s.addDigits(1))
----------------------------------------------------------
PS C:\Users\K\OneDrive\桌面\AUTOKI> & C:/Users/K/AppData/Local/Programs/Python/Python311/python.exe c:/Users/K/OneDrive/桌面/AUTOKI/think.py 2 0 1 PS C:\Users\K\OneDrive\桌面\AUTOKI>


"""最佳解"""


"""
Time Complexity :- BigO(1)

Space Complexity :- BigO(1)
"""


class Solution:
    def addDigits(self, num: int) -> int:
        if num == 0 : return 0
        if num % 9 == 0 : return 9
        else : return (num % 9)




"""
複雜
時間複雜度:O(logn^2)
用於遞歸迭代數字
空間複雜度:O(1)
"""
class Solution:
    def addDigits(self, num: int) -> int:
        while num > 9:
            sum = 0
            while num:
                sum += num%10
                num = num//10
               
            num = sum

        return num
   

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁