SHARE
TWEET

Untitled

a guest Oct 18th, 2019 103 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. vector<int> plusOne(vector<int>& digits) {
  7.     vector<int> res = digits;
  8.     int carry = 1;  //our 1 to add
  9.     for (int i=res.size()-1; i>=0; --i) {
  10.         if (carry > 0) {
  11.             int val = res[i] + carry;
  12.             carry = 0;
  13.             if (val > 9) {
  14.                 carry = 1;
  15.                 val = val % 10;
  16.             }
  17.             res[i] = val;
  18.         }
  19.         else
  20.             break;
  21.     }
  22.     if (carry > 0)
  23.         res.insert(res.begin(), carry);
  24.     return res;
  25. }
  26.  
  27. int main() {
  28.     vector<int> digits {9,9,9,9};//{1,2,3,4};
  29.     auto res = plusOne(digits);
  30.     for (int n : res)
  31.         cout << n << " ";
  32.     cout << "\n";
  33.     return 0;
  34. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top