Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
Analyse: To reduce complexity, if the current addition does not make carry, then stop pushing numbers into a stack.
1 class Solution { 2 public: 3 vector<int> plusOne(vector<int>& digits) { 4 vector<int> result; 5 vector<int> help; 6 int carry = 1; 7 int temp = 0; 8 9 for(int i = digits.size() - 1; i >= 0; i--){ 10 temp = digits[i] + carry; 11 12 if(temp >= 10){ 13 carry = 1; 14 temp %= 10; 15 } 16 else{ 17 carry = 0; 18 digits[i] = temp; 19 for(int j = i + 1; j < digits.size(); j++){ 20 digits[j] = help.back(); 21 help.pop_back(); 22 } 23 return digits; 24 } 25 help.push_back(temp); 26 } 27 if(carry == 1) help.push_back(1); 28 while(help.size()){ 29 result.push_back(help.back()); 30 help.pop_back(); 31 } 32 return result; 33 } 34 };