Plus One Solution

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.0 kB
1
Indexable
Never
class Solution {
public:
    vector<int> reverse(vector<int> nums) {
        int i = 0, j = nums.size() - 1;
        
        while (i < j) {
            int temp = nums[i];
            nums[i] = nums[j];
            nums[j] = temp;
            i++;
            j--;
        }
        
        return nums;
    }
    
    vector<int> plusOne(vector<int>& digits) {
        vector<int> reversedArray = reverse(digits);
        int carr = 1;
        
        for (int i = 0; i < reversedArray.size(); i++) {
            if (reversedArray[i] + carr > 9) {
                reversedArray[i] = 0;
                carr = 1;
            } else {
                reversedArray[i] += carr;
                carr = 0; // No more carr since the sum is < 9 (Nothing would be added to further digits)
                break; // Since we no longer need to add any more digit
            }
        }
        
        if (carr) {
            reversedArray.push_back(1);
        }
        
        return reverse(reversedArray);
    }
};