Plus One Problem & Solution

Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer.

See the plus one problem on LeetCode.

C++ Solution

#pragma GCC optimize("Ofast")
#pragma GCC optimization("unroll-loops")

static const int _=[](){std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();

class Solution {
public:
  vector<int> plusOne(vector<int>& digits) {
    int carryover = 1;

    for (int i = digits.size() - 1; i >= 0; --i) {
      digits[i] += carryover;
      carryover = digits[i] / 10;
      digits[i] %= 10;
    }

    if (carryover > 0) {
      digits.insert(digits.begin(), carryover);
    }

    return digits;
  }
};

Are you looking for a job?