標籤:except ++ car nts 兩種 hat single nat res
題目
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.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
解法一思路
思路很簡單,如果數組的最後一個元素小於9,最後一個元素直接加1,然後返回修改後的數組即可。如果數組的最後一個元素等於9,就判斷它之前的元素是否等於9,如果等於,則繼續往前找,直到找到最靠前的9的位置pos,此時又分為兩種情況,如果pos不為0,那麼說明數組的長度不需要變化,直接pos-1位置的元素加一即可,如果pos為0,那麼建立個長度加1的數組,且將第一個元素設定為1即可(int數組預設初始值為0)。
代碼
class Solution { public int[] plusOne(int[] digits) { int pos = digits.length - 1; int length = pos; int[] des = new int[length+2]; if(digits[pos] < 9) { ++digits[pos]; return digits; } else { digits[pos] = 0; while(pos-1 >= 0 && digits[pos-1] == 9 && pos-1 >= 0) { digits[pos-1] = 0; pos--; } if(pos > 0){ digits[pos-1]++; return digits; } else{ des[0] = 1; return des; } } }}
以上的代碼是自己寫的,不夠優雅,以下的代碼思路相同,但比較優雅
class Solution { public int[] plusOne(int[] digits) { for(int i = digits.length-1; i >= 0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] res = new int[digits.length+1]; res[0] = 1; return res; }}
解法二思路
可能用carry來記載有沒有進位。此種思路與[leetcode]67.Add Binary這道題思路很相似。
代碼
class Solution { public int[] plusOne(int[] digits) { if (digits.length == 0) return digits; int carry = 1, n = digits.length; for (int i = digits.length - 1; i >= 0; --i) { int sum = digits[i] + carry; digits[i] = sum % 10; carry = sum / 10; if (carry == 0) return digits; } int[] res = new int[n + 1]; res[0] = 1; return res; }}
[leetcode]66.Plus One