66. Plus One [LeetCode]

/**************************************************************************
 * 
 * 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luuyiran

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值