PS/LeetCode
[LeetCode] 7. Reverse Integer
판교토끼
2020. 4. 12. 13:44
728x90
https://leetcode.com/problems/reverse-integer/
Reverse Integer - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
제목 그대로 단순히 숫자를 거꾸로 뒤집는 문제이다.
처음 봤을 때는 고전적으로 %해가며 담는 것을 생각했으나 string 변환을 통해 뒤집는 것으로 생각을 바꾸었다.
atoi 함수를 이용했다(https://docs.microsoft.com/ko-kr/cpp/c-runtime-library/reference/atoi-atoi-l-wtoi-wtoi-l?view=vs-2019).
다만 처음에 뒤집었을 때 오버플로우의 상황을 생각하지 않아서 에러가 났었다. 문제에서 반환형이 string이 아닌 int형이었기 때문에 추가적으로 고민이 필요했다. 아마 이 때문에 앞 번호 Easy임에도 불구하고 20%대의 정답률을 보이는 것 같다.
strcmp를 이용해 체크하였다.
class Solution {
public:
int reverse(int x) {
//int to string
string source = to_string(x);
/*---overflow check---*/
if(source[0]!='-' && source.length() > 10)
return 0;
if(source[0]=='-' && source.length() > 11)
return 0;
string result = "";
/*---reverse---*/
for(int i=source.length()-1;i>=0;i--)
if(source[i]!='-')
result += source[i];
/*---overflow check---*/
if(result.length()==10) {
if(source[0]!='-' && strcmp(result.c_str(),"2147483647")>0)
return 0;
if(source[0]=='-' && strcmp(result.c_str(),"2147483648")>0)
return 0;
}
//string to int
int finalResult = atoi(result.c_str());
if(source[0]=='-')
finalResult *= -1;
return finalResult;
}
};
728x90