백준 1259 팰린드롬수 C++
2023. 9. 14. 11:37ㆍ알고리즘문제 풀이/백준
문제
어떤 단어를 뒤에서부터 읽어도 똑같다면 그 단어를 팰린드롬이라고 한다. 'radar', 'sees'는 팰린드롬이다.
수도 팰린드롬으로 취급할 수 있다. 수의 숫자들을 뒤에서부터 읽어도 같다면 그 수는 팰린드롬수다. 121, 12421 등은 팰린드롬수다. 123, 1231은 뒤에서부터 읽으면 다르므로 팰린드롬수가 아니다. 또한 10도 팰린드롬수가 아닌데, 앞에 무의미한 0이 올 수 있다면 010이 되어 팰린드롬수로 취급할 수도 있지만, 특별히 이번 문제에서는 무의미한 0이 앞에 올 수 없다고 하자.
입력
입력은 여러 개의 테스트 케이스로 이루어져 있으며, 각 줄마다 1 이상 99999 이하의 정수가 주어진다. 입력의 마지막 줄에는 0이 주어지며, 이 줄은 문제에 포함되지 않는다.
출력
각 줄마다 주어진 수가 팰린드롬수면 'yes', 아니면 'no'를 출력한다.
알고리즘 분류
팰린드롬수: 앞으로 읽어도, 뒤로 읽어도 같은 수이다.
한 자리 수는 무조건 팰린드롬수이다.
두 자리 수일 때는 10의 자리 수와 1의 자리 수가 같아야 한다.
세 자리 수일 때는 100의 자리 수와 1의 자리 수가 같아야 한다.
네 자리 수일 때는 1000의 자리수와 1의 자리수가 같아야 하고 100의 자리 수와 10의 자리수가 같아야 한다.
다섯 자리 수일 때는 10000의 자리수와 1의 자리수가 같아야 하고 1000의 자리수와 10의 자리수가 같아야 한다.
#include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
while (n != 0) {
// if n is one digit number, n is always the palindrome number,
if (n < 10) {
cout << "yes" << "\n";
}
//if n is two digit number
else if (n < 100) {
//if the tens'digit of n is the same as the unit digit of n,
//n is the palindrome number.
if (n % 10 == n / 10) {
cout << "yes" << "\n";
}
else {
cout << "no" << "\n";
}
}
//if n is three digit number
else if (n < 1000) {
//if the hundreds'digit of n is the same as the unit digit of n,
//n is the palindrome number.
if (n % 10 == n / 100) {
cout << "yes" << "\n";
}
else {
cout << "no" << "\n";
}
}
//if n is four digit number
else if (n < 10000) {
//if the thousands'digit of n is the same as the unit digit of n
//and the hundreds'digit of n is the same as the tens' digit of n,
//n is the palindrome number.
if ((n % 10 == n / 1000)&&((n/100)%10==(n/10)%10)) {
cout << "yes" << "\n";
}
else {
cout << "no" << "\n";
}
}
//if n is five digit number
else if (n < 100000) {
//if the ten thousands'digit of n is the same as the unit digit of n
//and the thousands'digit of n is the same as the tens' digit of n,
//n is the palindrome number.
if ((n % 10 == n / 10000) && ((n / 1000) % 10 == (n / 10) % 10)) {
cout << "yes" << "\n";
}
else {
cout << "no" << "\n";
}
}
cin >> n;
}
return 0;
}'알고리즘문제 풀이 > 백준' 카테고리의 다른 글
| 백준 1261 알고스팟 C++ (0) | 2023.09.14 |
|---|---|
| 백준 1260 DFS와 BFS C++ (0) | 2023.09.14 |
| 백준 1237 정ㅋ벅ㅋ C (1) | 2023.09.14 |
| 백준 1197 최소 스패닝 트리 C++ (0) | 2023.09.14 |
| 백준 1181 단어 정렬 C++ (0) | 2023.09.13 |