PS/leetcode
[leetcode] 7. Reverse Integer
AlephZero
2019. 4. 28. 21:34
문제
Given a 32-bit signed integer, reverse digits of an integer.
풀이
$ans$ 변수를 관리 하면서
ans = 10*ans + x%10;
x /=10;
를 반복하면 된다.
주의해야할 점은, boundary condition을 처리하는 것이다.
첫 줄을 계산할 때 INT_MAX를 넘거나 INT_MIN보다 작아지면 바로 return 해준다.
Time Complexity : $O(log n)$
코드
class Solution {
public:
int reverse(int x) {
int ans = 0;
while(x)
{
int num = x%10;
x/=10;
if(ans > INT_MAX/10 ||( ans == INT_MAX/10 && num>7))return 0;
if(ans < INT_MIN/10 || (ans == INT_MIN/10 && num<-8))return 0;
ans = ans*10+num;
}
return ans;
}
};