반갑습니다!

[백준] 1259 펠린드롬수 본문

알고리즘 문제 풀이

[백준] 1259 펠린드롬수

김덜덜이 2020. 10. 3. 02:21

풀이

인덱스 2개를 각각 양 끝을 가리키도록 초기화한 뒤, 서로 교차될 때까지 비교해주는 방식으로 해결했다. 이 때 구현을 쉽게 하기 위해서 숫자를 문자열로 입력받았다.

코드

C++

#include <iostream>
using namespace std;

int main() {
    while (true) {
        string tmp;
        cin >> tmp;
        if (tmp == "0") break;
        int len = tmp.length();
        int left = 0;
        int right = len - 1;
        bool is_palindrome = true;
        while (left <= right) {
            if (tmp[left] != tmp[right]) {
                cout << "no\n";
                is_palindrome = false;
                break;
            }
            left++;
            right--;
        }
        if (is_palindrome)
            cout << "yes\n";
    }
    return 0;
}

Python3

import sys

while True:
    tmp = sys.stdin.readline().rstrip()
    if tmp == '0':
        break
    left = 0
    right = len(tmp) - 1
    is_palindrome = True
    while left <= right:
        if tmp[left] != tmp[right]:
            print("no")
            is_palindrome = False
            break
        left += 1
        right -= 1
    if is_palindrome:
        print("yes")