알고리즘 문제풀이

LeetCode - Reverse Integer

오렌지색 귤 2022. 10. 25. 00:36
반응형

 

 

 

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

 

나의 풀이

class Solution {
    public int reverse(int x) {
        long absVal = x;
        if (absVal < 0) {
          absVal *= -1;
        }
        StringBuilder sb = new StringBuilder(String.valueOf(absVal));
        String reverse = sb.reverse().toString();
        long ans = Long.valueOf(reverse);
        if (x < 0) {
          ans *= -1;
        }
        if (ans < Integer.MIN_VALUE || ans > Integer.MAX_VALUE) {
          return 0;
        }
        return (int) ans;
    }
}

 

 

떠올린 방법

1. String 변환 및 long 타입 사용

- time complexity : O(log x)

- 32 bit integer만 사용해야 하는 환경인데 long type을 사용했으므로 틀린 풀이이다.

- 성능 또한 좋지 못하다

 

 


솔루션

1. Pop and Push Digits & Check before Overflow

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;
    }
}

- time complexity : O(log x)

- space complexity : O(1)

반응형