LeetCode | Plus One

题目:

Given a number represented as an array of digits, plus one to the number.


思路:

数组的遍历需要从右向左进行,然后结果存在临时数组中为从左向右。输出前遍历一半的数组将数组反序。

代码:

class Solution {
public:
    vector<int> plusOne(vector<int> &digits) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<int> v;
        
        int next = 1;
        for(int i = digits.size() - 1; i >= 0 ; i--)
        {
            int tmp = digits[i] + next;
            v.push_back(tmp%10);
            next = tmp/10;
        }
        
        if(next != 0)
        {
            v.push_back(next);
        }
        
        for(int i = 0; i < v.size()/2; i++)
        {
            int t = v[i];
            v[i] = v[v.size() - 1 - i];
            v[v.size() - 1 - i] = t;
        }
        return v;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11690411
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞