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.


题目标签:Array

  这道题目给了我们一个digits 的array, 这个array 等于一个数字,让我们加1。来分析一下,如果是不需要进位的 <9 , 那么直接加1就返回。如果是需要进位的,=9, 那么我们需要把目前的digit 改为0,接着继续检查前一位,因为你不确定前一位加1 是不是需要进位。一旦当我们找到不需要进位的那个digit, 加1 返回就可以了。如果碰到一种极端的情况,类似于 999 的话,那么我们 遍历完之后 是 000, 还需要一个1 ,所以要重新建立一个array, size + 1,把1 加在 [0]的位置。

Java Solution:

Runtime beats 39.20%

完成日期:04/05/2017

关键词:Array

关键点:特殊情况类似于999 需要重新建立一个array with size + 1 来放1在最左边

 class Solution
{
public int[] plusOne(int[] digits)
{
int[] res; // iterate digits from right to left
for(int i= digits.length - 1; i>=0; i--)
{
if(digits[i] == 9) // digit = 9
{
digits[i] = 0;
}
else // digit from 0 to 8
{
digits[i]++;
return digits; // after add 1 to digit, return
} } // coming here means the 1 is not yet added and also digits is finished
// there is only one case: 999...
res = new int[digits.length + 1];
res[0] = 1; return res;
}
}

参考资料:N/A

LeetCode 题目列表 - LeetCode Questions List

题目来源:https://leetcode.com/

05-11 09:29