首页 > 代码库 > Plus One

Plus One

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.

思路:需要考虑进位的情况。

 1 class Solution { 2 public: 3     vector<int> plusOne( vector<int> &digits ) { 4         int carry = 1; 5         for( size_t i = digits.size(); i != 0; --i ) { 6             if( ++digits[i-1] == 10 ) { 7                 digits[i-1] = 0; 8                 carry = 1; 9             } else {10                 return digits;11             }12         }13         digits.insert( digits.begin(), 1 );14         return digits;15     }16 };

 

Plus One