본문 바로가기
PS(Problem Solving)/백준_BOJ

[백준] 4096번 - 팰린드로미터 (C++) 문제 및 풀이

by 초코칩프라푸치노 2022. 2. 22.

문제) 백준 - 구현 - 팰린드로미터

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

 

4096번: 팰린드로미터

입력은 여러 테스트 케이스로 이루어져 있다. 각 테스트 케이스는 한 줄로 이루어져 있고, 현재 승환이의 주행 거리계에 적혀있는 수가 주어진다.이 숫자는 2자리와 9자리 사이(포함)이다. 예를

www.acmicpc.net

 

주어진 숫자열을 팰린드롬으로 만들 수 있는 가장 최소 거리를 출력하는 문제였습니다.

알고리즘은 다음과 같습니다.

팰리드롬 검사 → (string)000121  →  (int)121  →  +1  →  (int)122 →  (string)000122  →  팰린드롬 검사 → ...

 

C++ 소스코드)

#include <bits/stdc++.h>
#define endl "\n"
using namespace std;
bool isPld(string str){
for(int i=0;i<str.size()/2;i++){
if(str[i]!=str[str.size()-1-i]){
return false;
}
}
return true;
}
string itos(string str,int n){
string temp = to_string(n);
while(temp.size()<str.size()){
temp= "0" + temp;
}
return temp;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
string t;
while(1){
cin >> t;
if(t == "0")
break;
int cnt = 0;
while(!isPld(t)){
cnt++;
int temp = stoi(t);
temp++;
t = itos(t, temp);
}
cout << cnt << endl;
}
return 0;
}
view raw 4096.cpp hosted with ❤ by GitHub
반응형

댓글