본문 바로가기

문제 풀이/문제 풀이(BOJ)

[Silver V] 회문인 수 - 11068

[문제 위치]

https://www.acmicpc.net/problem/11068

[문제 풀이]

이 코드는 입력받은 정수 N이 2진법부터 64진법까지의 어느 진법으로 표현되었을 때 회문이 되는지 확인한다. 먼저 to_base 함수는 주어진 숫자를 해당 진법으로 변환해 문자열로 반환하며, is_palindrome 함수는 해당 문자열이 앞뒤로 같은지를 검사한다. main 함수에서는 각 테스트 케이스마다 2부터 64까지의 진법을 시도하면서 회문이 되는 경우가 있는지를 찾아, 하나라도 있으면 1을, 없으면 0을 출력한다.

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

string to_base(int num, int base) {
    const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
    string result;
    while (num > 0) {
        result += digits[num % base];
        num /= base;
    }
    reverse(result.begin(), result.end());
    return result;
}

bool is_palindrome(const string& s) {
    int left = 0, right = s.size() - 1;
    while (left < right) {
        if (s[left++] != s[right--]) return false;
    }
    return true;
}

int main() {
    int T;
    cin >> T;
    while (T--) {
        int N;
        cin >> N;
        bool found = false;
        for (int base = 2; base <= 64; ++base) {
            if (is_palindrome(to_base(N, base))) {
                found = true;
                break;
            }
        }
        cout << (found ? 1 : 0) << endl;
    }
    return 0;
}