why this c++ code RE?


  • 0
    R
    
    class Solution {
    public:
        int reverse(int x) {
            vector<int> bits;
            long long res=0;
            bool fu=false;
            if(x>INT_MAX||x<INT_MIN)return 0;
            if(x<0){
                x=-x;
                fu=true;
            }
            
            int temp=x;
            int range=1;
            while(temp>=range){
                int bit = temp%(10*range)/range;
                bits.push_back(bit);
                range*=10;
            }
            for(int i=0;i<bits.size();i++){
                if(!fu){
                    if(-(res*10+bits.at(i))<INT_MIN)
                        return res*10+bits.at(i);
                }else{
                    if(res*10+bits.at(i)>INT_MAX)
                        return 0;
                }
                res=res*10+bits.at(i);
            }
            
            if(fu){
                return -res;
            }
            else{
               return res;
            }
        }
    };
    

  • 0
    R

    ok...I figured it out just now, it is my variable int range over flow. Change to long long and it will be accepted.


Log in to reply
 

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