LeetCode # Array # Easy # 66. Plus One

题目:

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

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

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

思路:主要是对个位=9或者全部=9的case的处理要想清楚。

 1 class Solution {
 2     public int[] plusOne(int[] digits) {
 3         int size = digits.length;  
 4         int sum = 0;  
 5         for (int i = size - 1; i >= 0; i--){  //从个位开始
 6             sum = digits[i] + 1;  
 7             if (sum == 10) { //如果当前数=9,则sum=10,则应该进1位,所以当前为置为0.前一位+1.
 8                 digits[i] = 0; continue;
 9             }  
10             else { //否则,跳出循环
11                 digits[i] = sum; break;
12             }  
13         }  
14         if (sum == 10){  //如果最高位=9,则sum=10.此时,应该建一个数组,比digital大一位,然后将digital拷贝至该数组。
15             int[] result = new int[size + 1];  
16             for (int j = 0; j < size; j++)  
17                 result[j + 1] = digits[j];  
18             result[0] = 1;  
19             return result;  
20         }  
21         else  
22             return digits;
23     }
24 }

参考:https://blog.csdn.net/sunshine0_0/article/details/54917835

猜你喜欢

转载自www.cnblogs.com/DongPingAn/p/8982430.html