배움 저장소

[Leet Code]009 Palindorme Number 본문

PS/LeetCode

[Leet Code]009 Palindorme Number

시옷지읏 2021. 5. 21. 20:34

 

첫 풀이. 벡터안에 값을 저장하고 투포인터로 비교한다.

#include <string>
#include <vector>

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        if(x<10) return true;
        
        vector<int> order;
        while(x>0)
        {
            order.push_back(x%10);
            x/=10;
        }
                
        int size = order.size();
        for(int i=0; i<=(size-1)/2; ++i)
        {
            if(order[i] != order[size-1-i])
                return false;
        }
        return true;
    }
};

 

 disccusion 탭에서 도움을 얻은 풀이. 가운데 숫자를 기준으로 앞, 뒤로 나누어 비교한다. 같은 값인지 비교하여 T/F를 반환하면 된다.

 9이하의 숫자는 x==sum/10 구문에서 걸러진다. sum/10은 0이되므로 일의 자리 숫자는 모두 T가 반환된다.

class Solution {
public:
    bool isPalindrome(int x) {
        if(x<0) return false;
        if(x>=10 && x%10==0) return false;
        
        int sum = 0;
        while(x>sum)
        {
            sum = sum*10 + x%10;
            x /= 10;
        }
        return x==sum || x==sum/10;
    }
};
Comments