Wednesday, August 5, 2020

LeetCode [7] Reverse Integer

7. Reverse Integer
Easy

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

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

//C++
class Solution {
public:
    int reverse(int x) {
        if(x==0) return 0;
        int sign = x>=0?1:-1;
        string s = to_string(x);
        std::reverse(s.begin(), s.end());
        int p = s.find_first_not_of('0');
        s = s.substr(p, s.size()-p);
        if(sign<0) s = "-"+s;
        long long y = stoll(s);
        if (y>INT_MAX || y<INT_MIN) return 0;
        return y;
    }
};

//Java
class Solution {
    public int reverse(int x) {
        long xl = Math.abs(x), ret = 0;
        long sign = x>=0?1:-1;
        while(xl>0){
            ret = ret*10+xl%10; 
            xl /= 10;
        }
        if(ret*sign>(long)Integer.MAX_VALUE || ret*sign<(long)Integer.MIN_VALUE) return 0;
        return (int)ret*(int)sign;
    }
}

No comments:

Post a Comment