Solution in C++


  • 1
    D

    we can slove this problem like Hexadecimal conversion

    MY CODE

    class Solution {
    public:
       int reverse(int x) {
            long long ans = 0;  //use long long for avoid overflow
            while(x)
            {
                ans = ans * 10 + x % 10;
                x /= 10;
            }
            if(x < 0) ans = ans * (-1);
            return ans > INT_MAX || ans < INT_MIN ? 0 : ans;
        }
    };
    

    note :
    because the answer maybe greater than 32-bit,so we should use long long insteat of int

    A controversial code

    class Solution {
    public:
        int reverse(int x) {
            int dir = 1;
            long long result = 0;
            if(x < 0) 
            {
                dir = -1;
                x = -1 * x;
            }
            while(x)
            {
                result = result * 10 + (x % 10);
                x = x / 10;
            }
            result = result * dir;
            return (result < INT_MIN || result > INT_MAX) ? 0 : result;
        }
    };
    

  • 0
    X
    This post is deleted!

  • 0
    M

    @DongChengrong When you do x = -1 * x; it will overflow for x == INT_MIN i.e. for x == -2147483648 result for x = -1 * x will be still non-positive -2147483648 due to overflow and later you will give wrong answer.


  • 0
    D

    @moytrage You are right,I will improve my algorithm.thanks you


  • 0
    N

    @moytrage said in Solution in C++:

    @DongChengrong When you do x = -1 * x; it will overflow for x == INT_MIN i.e. for x == -2147483648 result for x = -1 * x will be still non-positive -2147483648 due to overflow and later you will give wrong answer.

    How to solve it?


  • 0
    D

    @nijataa Don't worry! I use long long ,2 ^ 64,So if x = -1 * x will not overflow.But i think it isn't a good solution, so I will construct a better method to slove this problem


  • 0
    D
    This post is deleted!

Log in to reply
 

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