[백준/C++] 1259번:

문제로 이동

(백준/C++) 1259번: 회문수

1259: 회문수

입력은 여러 테스트 케이스로 구성되며 각 라인에 대해 1에서 99999 사이의 정수가 지정됩니다.

입력의 마지막 줄은 0이 되고 해당 줄은 문제에 포함되지 않습니다.

www.acmicpc.net


설명

1. reverse() 함수로 해결

이는 알고리즘 헤더 파일의 reverse() 함수를 사용하여 쉽게 해결할 수 있습니다.

2. reverse() 함수를 사용하지 않고 해결하는 방법

첫 번째 값과 마지막 값은 루프를 통해 순차적으로 비교됩니다.


암호

1. reverse() 함수로 해결

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

using namespace std;

int main()
{
	cin.tie(NULL);
	ios::sync_with_stdio(false);

	while (1)
	{
		string num;
		cin >> num;

		string compare = num; // 뒤집은 값을 저장할 배열을 하나 더 선언

		reverse(num.begin(), num.end()); // 수를 앞 뒤로 뒤집는다.

if (num == "0") // 0이 입력되면 중단 { break; } else if (num == compare) // 원본과 뒤집은 값이 같으면 { cout << "yes" << "\n"; // yes 출력 } else // 다르면 { cout << "no" << "\n"; // no 출력 } } return 0; }

2. reverse() 함수를 사용하지 않고 해결하는 방법

#include <iostream>
#include <string>

using namespace std;

int main()
{
	cin.tie(NULL);
	ios::sync_with_stdio(false);

	while (1)
	{
		string num;
		cin >> num;

		int num_len = num.length() - 1; // num의 끝자리 위치 저장

		bool flag = true; // 팰린드롬수 판별 변수

		if (stoi(num) == 0)
		{
			break;
		}
		for (int i = 0; i < num.length() / 2; i++)
		{
			if (num(i) == num(num_len - i)) // 비교하는 값이 같다면
			{
				continue; // 계속 진행
			}
			else // 다르다면
			{
				cout << "no" << "\n"; // no 출력
				flag = false; // 팰린드롬 수가 아니므로 false
				break; // 반복문 빠져나감
			}
		}
		if (flag == true) // true의 값이 바뀐 것이 없다면 팰린드롬 수이므로,
		{
			cout << "yes" << "\n"; // yes 출력
		}
	}
	return 0;
}