首页 > 代码库 > [leetcode]Plus One

[leetcode]Plus One

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.

算法思路:

只有当该数组元素全是9的时候才产生进位,即:每一个元素都产生进位,一直到第0个元素还产生进位的时候,数组才需要扩展。一旦遇到哪个元素不需要进位,则返回结果。

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