/**************************************************************************
*
* 66. [Plus One](https://leetcode.com/problems/plus-one/)
*
* Given a non-empty array of decimal digits representing a non-negative integer,
* increment 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 contains a single digit.
* You may assume the integer does not contain any leading zero, except the number 0 itself.
*
* Example 1:
* Input: digits = [1,2,3]
* Output: [1,2,4]
* Explanation: The array represents the integer 123.
*
* Example 2:
* Input: digits = [9,9]
* Output: [1,0,0]
* Explanation: The array represents the integer 99.
*
* Example 3:
* Input: digits = [0]
* Output: [1]
*
* Similar Questions:2、67
**************************************************************************/
/// C++
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
add(digits, 1);
return digits;
}
private:
void add(vector<int>&digits, int one) {
int carry = one;
for (auto i = digits.rbegin(); i != digits.rend(); ++i) {
*i += carry;
carry = *i / 10;
*i %= 10;
}
if (carry > 0)
digits.insert(digits.begin(), 1);
}
};
/// C
/**
* reuse void add_to_string(char *string, char num, int index); of ./problems/43.Multiply Strings.cpp
*/
static void plusNumAt(int* digits, int index, char num) {
if (index < 0) return;
int sum = digits[index] + num;
int cur = sum % 10;
int carry = sum / 10;
digits[index] = cur;
if (carry)
plusNumAt(digits, index - 1, carry);
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* plusOne(int* digits, int digitsSize, int* returnSize){
int *res = (int *)malloc((digitsSize + 1) * sizeof(int));
res[0] = 0;
for (int i = digitsSize; i > 0; i--)
res[i] = digits[i-1];
plusNumAt(res, digitsSize, 1);
if (res[0] == 0) {
for (int i = 0; i < digitsSize; i++)
res[i] = res[i+1];
*returnSize = digitsSize;
return res;
}
*returnSize = digitsSize + 1;
return res;
}