leetcode easy
7. Reverse Integer
msna
2019. 2. 28. 23:10
https://leetcode.com/problems/reverse-integer/
Given a 32-bit signed integer, reverse digits of an integer.
32비트의 부호있는 정수가 있다, 정수의 숫자를 반전시켜라.
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비트의 부호있는 정수 범위[−231, 231 − 1]의 환경이라고 가정하자.
이 문제의 목적을 위해 반전된 정수가 오버플로우 되면 0을 반환하는 것으로 가정한다.
푸는 방법은 2가지가 있는데 데이터를 문자로 취급해서 처리하는 방법과 수치로 취급해서 처리하는 방법이 있다.
문자로 처리하는 방법 :
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int reverseByChar(int x) { | |
// 숫자가 0이면 반전해도 0이기 때문에 0을 리턴한다. | |
if( x == 0 ){ | |
return 0; | |
} | |
StringBuilder sb = new StringBuilder(); | |
// 문자열로 처리할 땐 음수인 판단하여 "-"를 먼저 더한다. | |
if( x < 0 ){ | |
sb.append( "-" ); | |
} | |
// 숫자를 문자열로 바꾸고, 문자열의 마지막부터 sb에 더한다. | |
// 음수의 경우 마지막 순서에 "-"가 나오는데 break를 해서 sb.append를 피한다. | |
char[] xCharArray = String.valueOf( x ).toCharArray(); | |
for( int ridx = xCharArray.length - 1 ; ridx >= 0; ridx-- ){ | |
char ch = xCharArray[ridx]; | |
if( ch == '-' ){ | |
break; | |
} | |
sb.append( ch ); | |
} | |
// 파싱한 값이 정수범위를 넘어설 수 있으므로 long으로 계산하고 그 결과가 정수 범위인지 판한단다. | |
long reverseX = new BigDecimal( sb.toString() ).longValue(); | |
if( reverseX > Integer.MAX_VALUE || reverseX < Integer.MIN_VALUE ){ | |
return 0; | |
} | |
return (int) reverseX; | |
} |
수치를 계산하여 처리하는 방법 :
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static int reverseByCalc( int x ){ | |
// 숫자가 0이면 반전해도 0이기 때문에 0을 리턴한다. | |
if( x == 0 ){ | |
return 0; | |
} | |
// 나머지 연산자를 이용하여 x의 가장 낮은 자릿수 숫자를 구하고, | |
// 그 숫자를 reverseX에 더해주는데, 기존 reverseX를 10곱한 값에 더해준다. | |
// x는 1/10씩 작아지고 reverseX는 10배씩 커진다고 보면 된다. | |
long reverseX = 0; | |
while( x != 0 ){ | |
int mod = x % 10; | |
x = x / 10; | |
reverseX = ( reverseX * 10 ) + mod; | |
} | |
// 자바의 경우 Integer는 32비트 고정이라 이런 식이 필요 없지만, | |
// Integer.MAX_VALUE, Integer.MIN_VALUE가 64비트값이라면 이런식으로 처리해주면 된다. | |
double MIN_32BIT_INT = Math.pow( -2, 31 ); | |
double MAX_32BIT_INT = Math.pow( 2, 31 ) - 1; | |
if( reverseX < MIN_32BIT_INT || MAX_32BIT_INT < reverseX ){ | |
return 0; | |
} | |
return (int) reverseX; | |
} |
leetcode에서 위 방법들을 처리하면 문자는 28ms, 숫자는 15ms에 실행이 된다.
간단한 프로토타입이라면 문자열로 처리해도 되지만 자주 사용되는 코드라면 숫자를 계산하는 코드를 써야겠다.