LeetCode #7 Reverse Integer

nathan·2022년 1월 12일
0

알고리즘문제

목록 보기
98/102

Reverse Integer

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).


Ex1:

  • Input: x = 123
  • Output: 321

Ex 2:

  • Input: x = -123
  • Output: -321

Ex 3:

  • Input: x = 120
  • Output: 21

Constraints

  • -2^31 <= x <= 2^31 - 1

Java code

class Solution {
    public int reverse(int x) {
        String strX = String.valueOf(x);
        StringBuffer sb = new StringBuffer();
        String tmp;
        long longAnswer;
        int answer = 0;

        if (x < 0){
            sb.append("-");
            tmp = strX.substring(1);
        } else {
            tmp = strX;
        }

        for (int i = tmp.length() - 1; i > -1; i--) {
            sb.append(tmp.charAt(i));
        }
        int maxInt = Integer.MAX_VALUE;
        int minInt = Integer.MIN_VALUE;
        
        longAnswer = Long.parseLong(String.valueOf(sb));
        if (minInt <= longAnswer && longAnswer <= maxInt){
            answer = (int) longAnswer;
        }

        return answer;
    }
}

풀이

  • 우선 입력받은 int x를 문자열로 바꾼다.
  • 만약 원래 int x가 음수라면 "-"를 스트링버퍼 값인 sb에 추가한다. 그리고 "-"기호를 뺀 부분을 String tmp에 넣는다.
  • int x가 양수라면 그대로 String tmp에 넣는다.
  • tmp길이만큼 for문을 역순으로 돌면서 sb에 값을 추가한다.
  • 해당 값이 integer 범위를 넘어설 수 있으므로 longAnswer란 값을 만들어 sb를 넣는다.
  • 이 값이 integer를 넘으면 0을 반환, 아니라면 int로 캐스팅하여 값을 반환한다.

profile
나는 날마다 모든 면에서 점점 더 나아지고 있다.

0개의 댓글