My C++ code (8ms, only int with overflow detection)


  • 0
    D

    Just do overflow detection in each iteration: the overflow happens when (INT_MAX - newdigit)/10 < res

    class Solution {
    public:
        int reverse(int x) {
            int res=0, newdigit,sign =1;
            if(x==INT_MAX || x==INT_MIN) return 0; 
            if(x<0) 
            {   sign = -1;
                x  = -x;
            }
            while(x)
            {
                newdigit = x%10;
                x = x/10;
                if((INT_MAX - newdigit)/10 >= res) res = res*10 + newdigit;
                else return 0;//sign>0?INT_MAX:INT_MIN;
            }
            return sign>0?res:-res;
        }
    };

  • 0
    E

    When the max number divide 10,it lost its last number.Is there no special situation to make it wrong?How to prove it。


Log in to reply
 

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