Written by JS970
on
on
1259 - 팰린드롬수
- 난이도: 브론즈 1
- 날짜: 2023년 2월 4일
- 상태: Correct
- 추가 검토 여부: Yes
solution
- 숫자를 입력받은 뒤 10을 곱하는 과정을 통해 몇 자릿수인지 알아낸 후 동적 할당을 통해 해당 자릿수만큼의 크기를 가지는 배열을 생성했다.
- 이 배열의 첫 번째 원소와 마지막 원소를 시작으로, 두 번째 원소와 마지막에서 두 번째 원소 … 순으로 탐색하여 서로 다른 숫자가 있는지 탐색했다.
- 이를 바탕으로 요구사항에 맞게 출력했다.
- string으로 입력받은 뒤 algorithm의 reverse를 사용하여 문자열을 reverse한 후 이를 비교하면 훨씬 간단하게 풀 수 있다.
code
#include <iostream>
using namespace std;
int main()
{
int input;
while(1)
{
cin >> input;
if(input == 0) break;
int i = 1;
int cnt = 0;
while(input / i != 0)
{
cnt++;
i *= 10;
}
int * arr = new int[cnt];
int div = 1;
for(int i = 0; i < cnt - 1; i++)
div *= 10;
for(int i = 0; i < cnt; i++)
{
arr[i] = input / div;
input -= arr[i] * div;
div /= 10;
}
int start = 0;
int end = cnt-1;
bool palindrome = true;
while(start <= end)
{
if(arr[start] != arr[end])
{
palindrome = false;
break;
}
start++;
end--;
}
if(palindrome) cout << "yes" << endl;
else cout << "no" << endl;
}
return 0;
}
-
reverse사용 코드
#include <iostream> #include <algorithm> using namespace std; int main() { string N; while (N != "0") { cin >> N; string M = N; reverse(N.begin(), N.end()); if (N != "0") { if (N == M) { cout << "yes\n"; } else { cout << "no\n"; } } } return 0; }
ref
- reverse 사용 코드