iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python实现"加一"的两种方法
  • 952
分享到

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

两种方法Python 2023-01-31 01:01:00 952人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

给定一个非空的数值数组代表一个非负整数,对整数进行加一操作 整数最高位存放在数组头位,数组中每一个元素都代表一个数字 你可以认为整数不以0开头,除了数字0以外 Example 1: Input: [1,2,3] Output: [1,

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

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

你可以认为整数不以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:翻转数组进行加一计算,输出再次翻转后的数组


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:数组转整数,加一后再转数组


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/

--结束END--

本文标题: Python实现"加一"的两种方法

本文链接: https://www.lsjlt.com/news/184424.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作