前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode: explore-array-27 加一

leetcode: explore-array-27 加一

作者头像
用户7685359
发布2020-08-21 19:49:07
3500
发布2020-08-21 19:49:07
举报
文章被收录于专栏:FluentStudyFluentStudy

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

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

题目分析

原题内容如下:

代码语言:javascript
复制
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 实现相当的简单,一句话搞定,参考代码如下:

参考代码如下:

代码语言:javascript
复制
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 中列表和字符串的转换很简单,在这个题目中我们就用到了,代码如下:

代码语言:javascript
复制
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 类型,否则会报错

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

代码语言:javascript
复制
while nums != 0:
    print(nums % 10)
    nums //= 10

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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 FluentStudy 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目分析
  • 参考答案
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档