알고리즘/LeetCode(easy)

7. Reverse Integer

SummerEda 2019. 12. 18. 10:37
LeetCode 영어 문제

 

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.

 

번역

 

32 비트 부호있는 정수가 주어지면 정수의 반대 자릿수입니다.

예 1 : 입력 : 123 출력 : 321

예 2 : 입력 : -123 출력 : -321

예 3 : 입력 : 120 출력 : 21

노트 : 32 비트 부호있는 정수 범위 [-231, 231-1] 내의 정수만 저장할 수있는 환경을 처리한다고 가정합니다. 이 문제의 목적을 위해, 역 정수가 오버 플로우 될 때 함수가 0을 리턴한다고 가정하십시오.

 

다른 사람들의 풀이

 

class Solution {
    public int reverse(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
            if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
            rev = rev * 10 + pop;
        }
        return rev;
    }
}
    public int reverse(int x) {
        int result = 0;
        while(x != 0){
            int remain = x % 10;
            int tmp = result * 10 + remain;
            if(result != (tmp - remain) /10) {
                return 0;
            }
            result = tmp;
            x = x / 10;
        }
        return result;
    }
class Solution {
    public int reverse(int x) {
        long rev = 0;
        while (x != 0) {
            rev = 10 * rev + x % 10;
            x = x / 10;
        }
        return rev > Integer.MAX_VALUE || rev < Integer.MIN_VALUE
               ? 0
               : (int) rev;
    }
}
class Solution {
    public int reverse(int x) {
        int prevRev = 0;
        int rev = 0;
        while (x != 0) {
            rev = 10 * rev + x % 10;
            if ((rev - x % 10) / 10 != prevRev) {
                return 0;
            }
            prevRev = rev;
            x = x / 10;
        }
        return rev;
    }
}

 

풀이

 

 

 

출처 sources
 

Reverse Integer - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com