leetcode66加一(python實現)

1.問題描述


給定一個由整數組成的非空數組所表示的非負整數,在該數的基礎上加一。

最高位數字存放在數組的首位, 數組中每個元素只存儲一個數字。

你可以假設除了整數 0 之外,這個整數不會以零開頭。

示例 1:

輸入: [1,2,3]
輸出: [1,2,4]
解釋: 輸入數組表示數字 123。
示例 2:

輸入: [4,3,2,1]
輸出: [4,3,2,2]
解釋: 輸入數組表示數字 4321。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/plus-one

2.python求解


 1.我的思路,把list數組中每個元素乘以10的N次方的形式累加,轉爲int。對於Int+1再轉爲list

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        l = len(digits)
        r_sum = 0
        for i in range(l):
            r_sum += digits[i]*pow(10,l-i-1)
        return map(int,str(r_sum+1))

 2.其他思路,逆序處理List,

首先對最後一個數值元素+1。

  • 如果+1後小於10,則直接返回digits
  • 如果加1後等於10,則置爲0,下面分兩種情況:
    • 如果這個元素是第一個元素,則需要往前補一個1
    • 如果這個元素不是第一個元素,就置爲0後,往前的一個元素+1;
class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        for i in range(len(digits)-1,-1,-1):
            digits[i] += 1
            if digits[i]==10:
                digits[i] = 0
                if i==0:
                    digits.insert(0,1)
            else:
                break
        return digits

3.python知識點補充


 1.關於N次冪

  • 表示10的N次冪,可以用e來表示
>>> 1e5
100000.0
>>> 2e5
200000.0
>>> 2e-5
2e-05
>>> 2e-1
0.2

  • pow(x,y)返回 xy(x的y次方) 的值。好像不用import math耶
>>> pow(2,5)
32
>>> pow(2,1/2)
1.4142135623730951
>>> pow(10,3)
1000
  • map函數,

    map() 會根據提供的函數對指定序列做映射。

    第一個參數 function 以參數序列中的每一個元素調用 function 函數,返回包含每次 function 函數返回值的新列表。


map(function, iterable, ...)

    Return an iterator that applies function to every item of iterable, 
yielding the results. If additional iterable arguments are passed, 
function must take that many arguments and is applied to the items from all iterables in parallel.
 With multiple iterables, the iterator stops when the shortest iterable is exhausted. 

For cases where the function inputs are already arranged into argument tuples, 
see itertools.starmap().

>>>def square(x) :            # 計算平方數
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 計算列表各個元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函數
[1, 4, 9, 16, 25]
 
# 提供了兩個列表,對相同位置的列表數據進行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

這裏用map函數把int類型的一個整數,轉爲List
# num = 12345
# num_list = [1,2,3,4,5]
num_list = map(int,str(num))
  • range函數,着重負數形式,這裏就不用把list逆序了,只需要逆序的索引來遍歷digits
兩種形式
1.range(N)得到[0,N-1],即[0,N),以1爲步長,左閉右包
2.range(start,stop,step),得到在[start,stop)以step爲步長的list,也是左閉右包哦
4.range(start,stop)得到在[start,stop)以1爲步長的list,也是左閉右包哦

幾個栗子

>>>range(10)        # 從 0 開始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)     # 從 1 開始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)  # 步長爲 5
[0, 5, 10, 15, 20, 25]
>>> range(0, -10, -1) # 負數
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

 


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章