[LeetCode] 2. Reverse Integer

2021. 2. 24. 20:52

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

Example 1:

Input: x = 123
Output: 321

Example 2:

Input: x = -123
Output: -321

Example 3:

Input: x = 120
Output: 21

Example 4:

Input: x = 0
Output: 0

정수를 역수 취하는 문제

생각해봐야 할것

  • 0이 맨앞으로 가면 없어짐
  • 자리수를 어떻게 구할지
  • 음수인 경우 표시 어떻게 해야할지

일단 가장 쉽게 떠오르는건

1) 정수값 String으로

2) String을 char배열로 만들기

3) char배열 역순 배치

4)char배열 String으로 바꾸기

5) String에서 int로 형변환

class Solution {
    public int reverse(int x) {

    String s = Integer.toString(x);
    char[] temp = new char[s.length()];
    String anw = "";
    for(int i =0;i<s.length();i++){
        temp[i] = s.charAt(s.length() - i -1);
    }

    for(char c : temp){
        anw += c;
    }

   int anwser = Integer.parseInt(anw);
        return anwser ;
    }
}
  • 문제점 : 음수인 경우가 안됨
class Solution {
    public int reverse(int x) {
        long r = 0;
        while (x != 0){
            r = (r * 10) + x % 10;
            x = x/10;
        }
        return (r < Integer.MIN_VALUE || r > Integer.MAX_VALUE) ? 0 : (int)r;
    }
}

고민하다가 도저히 생각이 안나서 찾아본 다른사람 코드

while문까지는 떠올릴 수 있었던 방법이지만 return이 이해가 안가서 정리를 해본다


return이 의미하는 바는 long타입의 r이 integer의 범위를 벗어나면 0을 출력한다는 의미이다.

Q)범위를 벗어나는 경우가 뭐가있을까? 혹시 아시는 분 있으면 댓글 부탁드립니다.

+ Recent posts