前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python实现"加一"的两种方法

Python实现"加一"的两种方法

作者头像
py3study
发布2020-01-10 14:37:41
1.4K0
发布2020-01-10 14:37:41
举报
文章被收录于专栏:python3

给定一个非空的数值数组代表一个非负整数,对整数进行加一操作

整数最高位存放在数组头位,数组中每一个元素都代表一个数字

你可以认为整数不以0开头,除了数字0以外

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:翻转数组进行加一计算,输出再次翻转后的数组

代码语言:javascript
复制
def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        extra = 0  #进位
        one = 1    #加一
        digits = digits[::-1]
        for index, num in enumerate(digits):
            if num+one+extra == 10:     #判断是否进位
                extra = 1
                one = 0
                digits[index] = 0
            else:     #不进位就直接输出
                digits[index] = num+one+extra
                return digits[::-1]
        digits.append(1)
        return digits[::-1]

2:数组转整数,加一后再转数组

代码语言:javascript
复制
def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        sum = 0
        for index, num in enumerate(digits):
            sum += num*(10**(len(digits)-index-1))
        sum += 1
        new_list = []
        for i in str(sum):
            new_list.append(int(i))
        return new_list

算法题来自:https://leetcode-cn.com/problems/plus-one/description/

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/07/29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1:翻转数组进行加一计算,输出再次翻转后的数组
  • 2:数组转整数,加一后再转数组
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档