C++ easy code, without long datatype


  • 1
    N
     int reverse(int x) {
            if (x == 0) {
                return 0;
            } else {
                int res = 0;
                int _x = abs(x);
                int flag = _x / x;
                while (_x > 0) {
                    int curr = _x % 10;
                    //in case overflow
                    if (res > (INT_MAX - curr) / 10) {
                       return 0;
                    } else  {
                        res  = res * 10 + curr;
                        _x = _x / 10;
                    }
                }
                return flag * res;
            }
        }

  • 0
    S

    There is no bussiness of positive or negative of x


  • 0
    Z

    seems no need in c++. i do not know exactly why. but in my test case it works.
    unlike in math, the result of an operation % is always positive.
    seems that in different operation in different languages when dealing with operator"%"
    in c++ or specifically in the LEETCODE's c++ compiler,
    -7%5 = -2;
    7%-5 = 2;
    -7%-5 = -2
    it directly depend on the positive of negative of 7. seems strange but it is the fact


  • 0
    S

Log in to reply
 

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