leetcode: explore-array-27 加一

时间:2022-07-23
本文章向大家介绍leetcode: explore-array-27 加一,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

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

题目分析

原题内容如下:

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

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