[LeetCode]66. Plus One

加1操作

Posted by JinFei on March 27, 2020

题目描述

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.

Example1:

  Input: [1,2,3]
    Output: [1,2,4]
    Explanation: The array represents the integer 123.

Example2:

  Input: [4,3,2,1]
    Output: [4,3,2,2]
    Explanation: The array represents the integer 4321.

解题思路

  • 本身用数字的加法操作 会造成溢出
  • 需要用到vector迭代
class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        int size = digits.size();
        vector<int> res(digits);
        int pos = size - 1;
        int carry = 0;
        while(pos >= 0){
            if(pos == size - 1){
                res[pos] += 1 + carry;
            }else{
                res[pos] += carry;
            }
            
            if(res[pos] >= 10){
                carry = res[pos] / 10;
                res[pos] = res[pos] % 10;
            }else{
                carry = 0;
            }
            pos--;
        }
        if(carry == 1){
            res.insert(res.begin(), 1); // 在开头的位置插入1 表明后面有进位
        }
        return res;
    }
};