栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

leetcode explore 初级算法第七题: 加一

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

leetcode explore 初级算法第七题: 加一

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

https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/25/

题目分析

原题内容如下:

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

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

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号