首页 > 其他 > 详细

(LeetCode)Plus One --- 加一

时间:2016-08-12 18:26:27      阅读:294      评论:0      收藏:0      [点我收藏+]

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.

Subscribe to see which companies asked this question


解题分析:

首先看到题目,没有看懂咋回事,这里给大家解释一下如何理解题意。

把一个list看成一个数字,比如说  [9, 9]

这里看成是99,然后加一,就是100,就是list , [1, 0, 0]

这里的处理方式可以从最后一位开始对每一位数组加一后进行判断是不是需要进位,

一个for如果有进位的话就加一,没有进位的话加0.

# -*- coding:utf-8 -*-
__author__ = 'jiuzhang'
class Solution(object):
    def PlusOne(self, digits):
        plus = 1
        for i in xrange(len(digits) - 1, -1, -1):
            digits[i] += plus

            if digits[i] >= 10:
                digits[i] -= 10
                plus = 1
            else:
                plus = 0
                break
        if i == 0 and plus == 1:
            digits.insert(0, 1)
        return digits





(LeetCode)Plus One --- 加一

原文:http://blog.csdn.net/u012965373/article/details/52188900

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!