第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定

leetcode explore 初級(jí)算法第七題: 加一

標(biāo)簽:
Python

leetcode explore 初级算法第五题。原题链接:

题目分析

原题内容如下:

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

题目意思很简单,我们可以拆解为以下几步:

1、输入一个列表,这个列表只包含数字
2、将这个列表从左到右的数字组合起来,组成一个大的数字
3、将组合后的数字加 1
4、将加1后的数字,换从左到右的顺序依次转为列表

参考答案

上面分析的题目步骤即是我们的答案,用 Python 实现相当的简单,一句话搞定,参考代码如下:

参考代码如下:

class Solution(object):
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        if not digits:
            return 0
        
        return list(str(int("".join([str(s) for s in digits])) + 1))

if __name__ == "__main__":
    s = Solution()
    print(s.plusOne([1, 2, 3]))
    print(s.plusOne([9, 9, 9]))

通过这个题目,我们可以总结以下几个知识点:

1、Python 中列表和字符串如何转换?转换时有何注意事项?
2、对于一个数字,如 12345,怎么通过数学方法,获取每一位上的数字?

首先第一个问题,Python 中列表和字符串的转换很简单,在这个题目中我们就用到了,代码如下:

s = "I am a String"
list_s = list(s)  # single char to list
list_s2 = s.split(" ")  # single word to list

s_copy = ",".join(list_s2)  # list to string

这里我们需要注意两点:

1、string to list,可以通过 list() 和 split() 两个方式来实现,根据业务需要灵活运用
2、list to string 时需要注意,列表里的元素必须要都是 string 类型,否则会报错

然后就是第二个问题,这个问题看上去很简单,在我们刚学习编程的时候,经常会做到类似的练习题,这里复习下,参考代码如下:

while nums != 0:
    print(nums % 10)
    nums //= 10

当然还有很多其他的实现,比如从高位开始计算等等,思路都是一样的。

點(diǎn)擊查看更多內(nèi)容
1人點(diǎn)贊

若覺(jué)得本文不錯(cuò),就分享一下吧!

評(píng)論

作者其他優(yōu)質(zhì)文章

正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得

100積分直接送

付費(fèi)專欄免費(fèi)學(xué)

大額優(yōu)惠券免費(fèi)領(lǐng)

立即參與 放棄機(jī)會(huì)
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)

舉報(bào)

0/150
提交
取消