66. Plus One
https://leetcode.com/problems/plus-one/description/
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.
Thoughts
两种情况: 遇到9变成0, 遇到其它数+1并返回.
Code
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
for i in range(len(digits) - 1, -1, -1):
if digits[i] != 9:
digits[i] += 1
return digits
digits[i] = 0
digits.insert(0, 1)
return digits
class Solution {
public int[] plusOne(int[] digits) {
for (int i = digits.length - 1; i >= 0; i--) {
if (digits[i] != 9) {
digits[i] += 1;
return digits;
}
digits[i] = 0;
}
int[] res = new int[digits.length + 1];
res[0] = 1;
return res;
}
}
Analysis
时间复杂度O(N).
Last updated
Was this helpful?