66. Plus One [LeetCode]

版权声明:QQ:872289455. WeChat:luw9527. https://blog.csdn.net/MC_007/article/details/80961005

Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

class Solution_66_1 {
public:
    vector < int > plusOne(vector < int >& digits) {
         add(digits, 1);
         return digits;
    }
private:
     void add(vector < int >&digits, int one) {
         int carry = one;
         for ( auto i = digits. rbegin(); i != digits. rend(); ++i) {
             *i += carry;
            carry = *i / 10;
             *i %= 10;
        }
         if (carry > 0)
            digits. insert(digits. begin(), 1);

    }
};

class Solution_66_2 {
public:
    vector < int > plusOne(vector < int >& digits) {
         add(digits, 1);
         return digits;
    }
private:
     void add(vector < int >&digits, int one) {
         int carry = one;
         for_each (digits. rbegin(), digits. rend(), [ &carry]( int &i) {
            i += carry;
            carry = i / 10;
            i %= 10; //最终i保留的大小
        });
         if (carry > 0)
            digits. insert(digits. begin(), 1);

    }
};

int main() {
    Solution_66_2 A;
    vector < int >a = { 9, 9, 9 };
    a = A. plusOne(a);
     for ( auto i : a)
        cout << i << " ";
    cout << endl;

     for_each(a. begin(), a. end(), []( int &i) {cout << i << ","; });



     while ( 1);
     return 0;
}

猜你喜欢

转载自blog.csdn.net/MC_007/article/details/80961005