fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> plusOne(vector<int>& digits) {
  5. int sum, carry = 0, n = digits.size();
  6. //add 1 to the last digit
  7. sum = digits[n - 1] + 1;
  8. //see if there is a carry generated
  9. if(sum > 9){
  10. carry = 1;
  11. digits[n - 1] = sum % 10;
  12. }else{
  13. //if no carry, add 1 to lsb and return
  14. digits[n - 1] = sum;
  15. return digits;
  16. }
  17. //if carry, keep adding till there is no carry
  18. for(int i = n - 2; i >= 0; i--){
  19. sum = digits[i] + carry;
  20. if(sum > 9){
  21. carry = 1;
  22. digits[i] = sum % 10;
  23. }else{
  24. //if no carry, return
  25. digits[i] = sum;
  26. return digits;
  27. }
  28. }
  29. //add 1 to the front if there is carry in the end
  30. if(carry){
  31. digits.insert(digits.begin(), 1);
  32. }
  33. return digits;
  34. }
  35.  
  36. int main() {
  37. int myints[] = {1, 2, 9};
  38. vector<int> v(myints, myints+3);
  39. vector<int> result = plusOne(v);
  40. for(int i = 0 ; i < result.size(); i++){
  41. cout << result[i];
  42. }
  43. cout << endl;
  44. return 0;
  45. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
130