Leetcode之Plus One 问题

问题描述:

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

You may assume the integer do not contain any leading zero, except the number 0 itself.

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

问题来源:Plus One (详细地址:https://leetcode.com/problems/plus-one/description/)

思路分析:题目的意思很简单,即使加一操作。回想一下,我们平时计算加一操作是怎么操作的啊?

情景一:从低位开始,如果最低位不是9,那就直接加一得到最终结果;

情景二:如果最后一位是9,则往前进一位,简单点说,就是这一位赋值为0,前面一位的数加一操作返回,但是,如果前面一位也是9呢?那就也赋为0,知道找到一个不为9的位加一返回不就是最终结果了吗?

情景三:如果所有位数都是9咋办?那我们就重新申请一个新数组,第一位赋值位1,其他位赋为默认值0不就完了吗?

代码:

Leetcode之Plus One 问题