릿코드(LEETCODE)

7. Reverse Integer - no solution

cepiloth 2020. 2. 9. 11:43
반응형

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

signed int n 을 리버스 하는 문제다.

reverse 했을때 int 유효범위가 넘어갈때 처리하는 방법이 키포인트인데 방법을 아직 못찾았다.

기록용으로 남겨 두자 나중에 풀자.

 

INT 유효범위 체크를 안한 틀린 코드

#include <algorithm>
class Solution {
public:
    int reverse(int x) {

        bool minus = false;
        if(x < 0) {
            minus = true;
        }
        
        x = abs(x);
        
        while(x) {
            int cand = x % 10;
            if(cand != 0)
                break;
            
            x = x / 10;
        }
        
        string s = to_string(x);
        
        std::reverse(s.begin(), s.end());
        
        long long sol = atol(s.c_str());
        if(minus) {
            sol *= -1;
        }
        return sol;
    }
};

 

INT 유효범위 추가한 코드

reverse 후 자료표현범위 체크 추가

#include <algorithm>
class Solution {
public:
    int reverse(int x) {

        bool minus = true;
        std::string s = std::to_string(x);
        if(s[0] == '-')
        {
            minus = false;
            s = s.substr(1, s.size()-1);
        }
        
        std::reverse(s.begin(), s.end());
    
        long num = atol(s.c_str());    
        num = minus ? num : -num;
        
        if (num > std::numeric_limits<int>::max() || num < std::numeric_limits<int>::min())
        {
            return 0;
        }
        
        return num;
    }
};

 

 

 

반응형