1. 题目描述

problem link

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.

2. 解题

先给最右边一位加1,如果有进位则依次往左进位,如果一直进到了最高位,则需要再malloc一个数组存放数据。

3. 代码

int* plusOne(int* digits, int digitsSize, int* returnSize) {
    for (int index = digitsSize - 1; index >= 0; index--) {
        if (digits[index] < 9) {
            digits[index]++;
            *returnSize = digitsSize;
            return digits;
        }

        digits[index] = 0;
    }

    // 如果走到这里,则需要再新malloc一个数组
    int* res = (int *)malloc(sizeof(int) * (digitsSize + 1));

    res[0] = 1;
    for (int i = 0; i < digitsSize; i++) {
        res[i + 1] = digits[i];
    }
    *returnSize = digitsSize + 1;
    return res;
}
Last modification:September 8th, 2019 at 08:23 pm