2023年10月27日 星期五

10/26 直式加法

The array-form of an integer num is an array representing its digits in left to right order.

  • For example, for num = 1321, the array form is [1,3,2,1].

Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k.

 

Example 1:

Input: num = [1,2,0,0], k = 34
Output: [1,2,3,4]
Explanation: 1200 + 34 = 1234

Example 2:

Input: num = [2,7,4], k = 181
Output: [4,5,5]
Explanation: 274 + 181 = 455

Example 3:

Input: num = [2,1,5], k = 806
Output: [1,0,2,1]
Explanation: 215 + 806 = 1021

 

Constraints:

  • 1 <= num.length <= 104
  • 0 <= num[i] <= 9
  • num does not contain any leading zeros except for the zero itself.
  • 1 <= k <= 104

 class Solution:

    def addToArrayForm(self, num: List[int], k: int) -> List[int]:
        n=len(num)

        i=-1
        n2=str(k)
        a=0 #進位

        while i >= -n:
            num[i]+=a
            print(f'加入進位 {num[i]}, i={i}')
            if i >= -(len(str(k))):
                y=int(n2[i])
                print()
                num[i] +=y
                print(num)
           
            if num[i] > 9:
                #進位
                a = 1
            else:
                a = 0
            num[i]%=10
            i-=1
        #確認k 是否加完
       
        while i >= -len(str(k)):
            if a:
                num.insert(0,1)
                a = 0
            else:
                num.insert(0,0)
            num[0] += int(n2[i])
            #確認是否進位
            if num[0] > 9:
                num[0] %= 10
                a=1
            i-=1
        if a:
            num.insert(0,1)




        return num

       
       

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

class Solution:
    def addToArrayForm(self, num: List[int], k: int) -> List[int]:
        carry = 0
        i = len(num) - 1
        result = []

        while i >= 0 or k > 0 or carry:
            x = num[i] if i >= 0 else 0
            y = k % 10 if k > 0 else 0
            total = x + y + carry
            carry = total // 10
            result.append(total % 10)

            i -= 1
            k //= 10

        return result[::-1]

       
       

       

標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁