LeetCode-66-Plus One

Posted 八行书

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-66-Plus One相关的知识,希望对你有一定的参考价值。

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.

 

题意:给定一个由数组表示的数字,加上一,返回由数组表示的结果

 

思路:

  参考Discuss的解法,对于每一位来说,只有等于9的时候才会进位,小于就的时候,数值加一然后返回本数组即可。

  如果最后数值进位后恰好比原值多一位,则直接new一个数组,默认值为0,赋值最高位为1,返回即可。

 

Java代码如下:

 1 public class Solution {
 2     public int[] plusOne(int[] digits) {
 3         if (digits.length==0)
 4             return digits;
 5         
 6         for (int i = digits.length -1; i>=0;i--) {
 7             if (digits[i] < 9) {
 8                 digits[i]++;
 9                 return digits;
10             }
11             digits[i] = 0;
12         }
13 
14         int[] res = new int[digits.length+1];
15         res[0] = 1;
16         return res;
17     }
18 }

 

以上是关于LeetCode-66-Plus One的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-66 Plus One

leetcode 66. Plus One

[LeetCode] 66. Plus One

[leetcode]66.Plus One

leetcode66 Plus One

[leetcode]66Plus One