A weird solution..


  • 0

    --Explaintion to my accepted answer

    • The involved question is how to handle overflow case. The Method below seems to have a "bug" although it passed all the test cases.
    • The so called "bug" depends on the equation 9*res=k*4294967295 exists a res([1000000003*9]<=[9*res]<=[2147483647*9]) and a k(k is a positive integer) that the equation holds.
    • But the fact is : (4294967295 % 9) != 0, and the interval [1000000003*9,2147483647*9] does not exist a number that equals k*4294967295(k=1,2,3,4). Then the code following is right, the "bug" actually does not exists.
    class Solution {
    public:
        int reverse(int x) {
            int res=0;
            int sign=(x>0)?1:-1;
            while(x){
                if((res*10/10) != res) return 0;
                res=res*10+sign*x%10;
                x/=10;
            }
            return sign*res;
        }
    };
    

Log in to reply
 

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