【LeetCode with Python】 Plus One

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/plus-one/
题目类型:模拟数值运算
难度评价:★
本文地址: http://blog.csdn.net/nerv3x3/article/details/37336603

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.


用一个int数组代表一个数值,最左边是最高位,现要求加上1,同样地返回一个int数组代表计算结果。
非常简单的模拟加法,注意进位问题,如果是99,999这种,最后加上1后还要在数组最左边插入一个元素1。
空间复杂度O(1)。时间复杂度O(N)。


class Solution:
    # @param digits, a list of integer digits
    # @return a list of integer digits
    def plusOne(self, digits):
        len_s = len(digits)
        carry = 1
        for i in range(len_s - 1, -1, -1):
            total = digits[i] + carry
            digit = int(total % 10)
            carry = int(total / 10)
            digits[i] = digit
        if 1 == carry:
            digits.insert(0, 1)
        return digits
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值