LeetCode 66. Plus One(加1)
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在最左邊
1 public class Solution 2 { 3 public int[] plusOne(int[] digits) 4 { 5 // check param validation. 6 if(digits == null || digits.length == 0) 7 returnnull; 8 9 int size = digits.length; 10 11 // iterate from right to left. 12 for(int i= size-1; i>=0; i--) 13 { 14 if(digits[i] < 9) // just add 1 and return digits array. 15 { 16 digits[i]++; 17 returndigits; 18 } 19 else 20 digits[i] = 0; 21 22 } 23 24 // it comes here, meaning the 1 hasn‘t been added. 25 int[] res = new int[size+1]; 26 res[0] = 1; // add 1 to the most left digit and all rest digits are 0. 27 28 return res; 29 } 30 }
參考資料:
https://discuss.leetcode.com/topic/24288/my-simple-java-solution
LeetCode 算法題目列表 - LeetCode Algorithms Questions List
LeetCode 66. Plus One(加1)