Why my code did not work?


  • 0
    W
    class Solution {
    public:
        vector<int> plusOne(vector<int>& digits) {
            int x = 0;
            vector<int> sol;
            for(int i = 0; i < digits.size(); i++){
                x = x * 10 + digits[i];
            }
            x += 1;
     
            while( x!= 0){
                sol.push_back(x%10);
                x = x/10;
            }
            
            reverse(sol.begin(), sol.end());
            return sol;
        }
    };
    

    I wrote this answer for this problem, but always get wrong answer for the case:

    Input:
    [9,8,7,6,5,4,3,2,1,0]
    Output:
    [1,2,8,6,6,0,8,6,1,9]
    Expected:
    [9,8,7,6,5,4,3,2,1,1]
    

    Does anybody have any idea where this error come from?
    Thanks !


  • 1
    K

    There is an integer overflow in your code.
    [9,8,7,6,5,4,3,2,1,0] is 9876543210 which is greater than INT_MAX.

    The int[] digits can be of any arbitrary size. Your approach isnt safe.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.