From : https://leetcode.com/problems/plus-one/
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int>::reverse_iterator rit = digits.rbegin();
if(rit != digits.rend()) {
int cur = *rit;
while(cur==9) {
*(rit++) = 0;
if(rit==digits.rend()) {
digits.insert(digits.begin(), 1);
return digits;
}
cur = *rit;
}
(*rit)++;
}
return digits;
}
};public class Solution {
public int[] plusOne(int[] digits) {
if (digits == null || digits.length == 0) {
return new int[] {};
}
int carry = 1;
for (int i = digits.length - 1; i>=0 && carry!=0; --i) {
int n = digits[i] + carry;
digits[i] = n % 10;
carry = n/10;
}
if (carry != 0) {
int[] ans = new int[digits.length+1];
ans[0] = 1;
System.arraycopy(digits, 0, ans, 1, digits.length);
return ans;
}
return digits;
}
}
本文详细阐述了如何通过编程实现给非负数表示的数组加上一的操作,包括反转数组、遍历并修改数字以及处理进位的情况。
1432

被折叠的 条评论
为什么被折叠?



