Given a 32-bit signed integer, reverse digits of an integer.
Note:
Assume we are dealing with an environment that 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.
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
Constraints:
- -231 <= x <= 231 - 1
문제 풀이:
easy인데 많이 틀렸다 ㅎㅎ
reversed된 숫자가 범위를 넘는지 체크하는게 어려웠다.
아래 처럼 result를 int로 선언해서 체크하는 방법도 있고
long으로 선언해서 마지막에 체크하는 방법도 있다.
class Solution {
public int reverse(int x) {
int result = 0;
while(x != 0){
int tmp = x % 10;
x /= 10;
if(result > Integer.MAX_VALUE/10 ||
(result == Integer.MAX_VALUE / 10 && tmp > 7 )) return 0;
if(result < Integer.MIN_VALUE/10 ||
(result == Integer.MIN_VALUE / 10 && tmp < -8 )) return 0;
result = result*10 + tmp;
}
return result;
}
}
long 선언
class Solution {
public int reverse(int x) {
long result = 0;
while(x != 0){
int tmp = x % 10;
x /= 10;
result = result*10 + tmp;
}
if(result > Integer.MAX_VALUE || result<Integer.MIN_VALUE){
return 0;
}
return (int)result;
}
}
'알고리즘 문제풀이 > leetcode' 카테고리의 다른 글
[leetcode 91] Decode Ways (0) | 2020.11.15 |
---|---|
[leetcode 8] String to Integer (atoi) (0) | 2020.11.15 |
[leetcode 387] First Unique Character in a String (0) | 2020.11.14 |
[leetcode 395] Longest Substring with At Least K Repeating Characters (0) | 2020.11.14 |
[leetcode 454] 4Sum II (0) | 2020.11.14 |
댓글