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:
Output: [1, 2, 4]
Output: [4, 3, 2, 2]
#include <vector>
#include <iostream>
std::vector<int> plusOne(std::vector<int>& digits) {
// Traverse the digits array starting from the last digit
int n = digits.size();
for (int i = n - 1; i >= 0; --i) {
// If current digit is less than 9, just add one and return the result
if (digits[i] < 9) {
digits[i]++;
return digits;
}
// Set current digit to 0 and continue to propagate the carry
digits[i] = 0;
}
// If all digits were 9, we will come out of the loop
// and all digits are now 0, we need an extra leading 1
digits.insert(digits.begin(), 1);
return digits;
}
int main() {
std::vector<int> digits1 = {1, 2, 3};
std::vector<int> result1 = plusOne(digits1);
for (int num : result1) {
std::cout << num << " ";
}
std::cout << std::endl;
std::vector<int> digits2 = {4, 3, 2, 1};
std::vector<int> result2 = plusOne(digits2);
for (int num : result2) {
std::cout << num << " ";
}
std::cout << std::endl;
std::vector<int> digits3 = {9, 9, 9};
std::vector<int> result3 = plusOne(digits3);
for (int num : result3) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
This implementation traverses the list from the end to the beginning, handling carries as described. If needed, it inserts a 1
at the start of the vector at the end.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?