https://leetcode.com/problems/reverse-integer/
문자열로 푸는 방식
class Solution {
public int reverse(int x) {
String reversed = new StringBuilder().append(Math.abs(x)).reverse().toString();
try{
return ( x < 0 ) ? Integer.parseInt(reversed) * - 1 : Integer.parseInt(reversed);
} catch (NumberFormatException e){
return 0;
}
}
}
숫자를 이용하는 방식
class Solution {
public int reverse(int x) {
int result = 0;
while( x != 0){
result = result * 10 + x % 10;
x = x/10;
}
if(result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
return 0;
} else {
return (int)result;
}
}
}
'Leetcode 100문제 도전' 카테고리의 다른 글
[Leetcode 6/100] Same Tree - Easy (0) | 2020.08.25 |
---|---|
[Leetcode 5/100] Roman to Integer - Easy (1) | 2020.06.29 |
[Leetcode 4/100] Palindrome Number - Easy (1) | 2020.06.28 |
[Leetcode 2/100] Add Two Numbers - Medium (0) | 2020.06.16 |
[Leetcode 1/100] Two Sum - Easy (0) | 2020.06.14 |