码迷,mamicode.com
首页 > 其他好文 > 详细

(LeetCode)Plus One --- 加一

时间:2016-08-12 18:27:20      阅读:195      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!