Link Search Menu Expand Document

7. Reverse Integer

Solution Code

C#

public class Solution {
    public int Reverse(int x) {
        bool isNegative = false;
        
        if (x < 0) {
            isNegative = true;
            x *= -1;
        }
        
        long rev = 0;
        
        for (; x > 0; rev = rev * 10 + (x % 10), x /= 10);
        
        if (rev > ((1L << 31) - 1))
            return 0;
            
        if (isNegative)
            rev *= -1;
            
        return (int)rev;
    }
}

C++

class Solution {
public:
    int reverse(int x) {
        signed long long rev = 0, num = x;
        bool is_negative = false;
        
        if (num < 0) {
            is_negative = true;
            num *= -1;
        }
        
        for (; num > 0; rev = rev * 10 + (num % 10), num /= 10);
        
        if (rev > ((1LL << 31) - 1))
            return 0;
            
        if (is_negative)
            rev *= -1LL;
            
        return (int)rev;
    }
};

Java

class Solution {
    public int reverse(int x) {
        boolean isNegative = false;
        
        if (x < 0) {
            isNegative = true;
            x *= -1;
        }
        
        long rev = 0;
        for (; x > 0; rev = rev * 10 + (x % 10), x /= 10);
        
        if (rev > ((1L << 31) - 1))
            return 0;
            
        if (isNegative)
            rev *= -1;
            
        return (int)rev;
    }
}

© 2023. All rights reserved.