Solution in C++


  • 0
    P

    class Solution {
    public:
    int reverse(int x) {

        bool negativeFlag = false;
        if (x < 0)
        {
            negativeFlag = true;
            x = -x ;
        }
        int reverse_number = 0;
        int previous_reverse_number = 0;
        int current_digit;
        
        while(x != 0)
        {
            current_digit = x % 10;
            reverse_number = (reverse_number*10) + current_digit;
            if (reverse_number / 10 != previous_reverse_number)
            {
                return 0;
            }
            previous_reverse_number = reverse_number;
            x = x / 10;
        }
        return (negativeFlag == true) ? -reverse_number : reverse_number;
    }
    

    };


Log in to reply
 

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