66. Plus One
class Solution { public int[] plusOne(int[] digits) { int length = digits.length - 1; while ( length >= 0){ if(digits[length] == 9){ digits[length] = 0; length--; }else{ digits[length]++; break; } } if(digits[0] == 0){ int[] result = new int[digits.length + 1]; result[0] = 1; return result; } return digits; } } ///// 129 130 //// 999 1000
Plus one : so
There are a case when the last one is 9, then 1 plus 9 is 0,
continue to check if the previous element is 9 or other numbers , if the prev is 9, then change it to 0 and continue to check the prev element,
If the prev element is not 9, then replace prev element with prev + 1. And break
in the cases 99 + 1, 999 + 1 , or 9999 + 1
100, 1000, 10000
The result array is one char longer than the original, in this case, we need to check if the index zero of the original array is 0 or not, if it’s 0, then we know it’s cases like above
99 + 1, 999 + 1 , or 9999 + 1
100, 1000, 10000
And we need to resize the original array and set the index 0 as 1, the default value for the rest of the array is 0. As we want it to be
A confusing and regular case, when 199 + 1 = 200
, it’s a regular case, no need to resize the array, even the last two chars are 9, and we have the last digit element changed to 0, and the second last changed to 0,
And we continue to see if the first digit is 9 or other digits, and its a regular digit, not 9, so we can just add 1 to the original number, we have 200, it doesn’t need to resize, because its 2, not 10 ,
https://www.youtube.com/watch?v=W95W3TELO9E&t=7s
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.
posted on 2018-07-18 09:44 猪猪🐷 阅读(369) 评论(0) 收藏 举报
浙公网安备 33010602011771号