Reverse Integer

2024. 10. 7. 16:47알고리즘/Leetcode

반응형

Solution

Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

 

Examples

Example 1:

Input: x = 123
Output: 321

 

Example 2:

Input: x = -123
Output: -321

 

Example 3:

Input: x = 120
Output: 21

 

Explanation

class Solution {
    public int reverse(int x) {
        boolean isNegative = false;
        if (x < 0) {
            isNegative = true;
            x = -x;
        }

        int res = 0;
        while (x > 0) {
            int digit = x % 10;
            x /= 10;
            if (res > (Integer.MAX_VALUE - digit) / 10) {
                return 0;
            }
            res = (res * 10) + digit;
        }

        return isNegative ? -res : res; 
    }
}

 

The variable, isNagative, is used for checking whether it is a positive number or not.

 

Inside the while loop, we repeatedly extract the last digit of x using the modulo operator '%',  and then update x by removing its last digit using integer division '/'. Also, we check if the reversed integer res exceeds the range of a 32-bit signed integer. If it does, we return 0 to indicate integer overflow. And add the digit to the current value of res multiplied by 10.

 

Lastly, if the original input integer x was negative, we return the reversed integer with a negative sign. Otherwise, we return the reversed integer as is.

 

반응형

'알고리즘 > Leetcode' 카테고리의 다른 글

Valid Anagram  (0) 2024.10.10
First Unique Character in a String  (2) 2024.10.08
Reverse String  (0) 2024.10.06
Valid Sudoku  (2) 2024.10.04
Two Sum  (1) 2024.09.24