[BaekJoon 1259][๐ค1] ํฐ๋ฆฐ๋๋กฌ์
โ ๋ฌธ์
๐ฏ ๋์ด๋
Bronze ๐ค1
๐ง ํ์ด
1. ๋ด ํ์ด (๋ฌธ์์ด)
- ์๊ณ ๋ฆฌ์ฆ
string
- ์ค๋ช
์ ์๋ฅผ ๋ฐ์์ string์ผ๋ก ๋ณํํ๊ณ , reverse ํ๋ ๋ฐฉ์์ ํ์ด์ด๋ค.
๋ฌธ์ ๋ฅผ ๋ณด์๋ง์ ๋ช๋ฒ์งธ ๋ฌธ์๋ฅผ ๋ฐ๊พธ๋ผ๋ ๊ฒ๋ ์๊ณ , ์ ์์ ํฌ๊ธฐ ์์ฒด๋ ํฌ์ง ์์์ ์ด ๋ฐฉ๋ฒ๋ถํฐ ๋ ์ฌ๋๋ค. ๊ทธ๋ฆฌ๊ณ ์ค์ ๋ก๋ ๊ฐ์ฅ ๋ง์ ์ฌ๋๋ค์ด ์ฌ์ฉํ ํ์ด์ด๊ธฐ๋ ํ๋ค.
์๊ฐ ๋ณต์ก๋๋ O(N)์ธ๋ฐ, reverse์ ์ฑ๋ฅ์ด ๋ฌธ์ ๊ฐฏ์์ ๋น๋กํ๊ธฐ ๋๋ฌธ์ด๋ค.
- ์ฝ๋
๋ด ํ์ด ์ฝ๋
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
while(true)
{
int iInput{};
cin >> iInput;
if(iInput == 0)
{
break;
}
string strInput{ to_string(iInput) }; // string์ผ๋ก ํ๋ณํ
string strTemp(strInput);
reverse(strInput.begin(), strInput.end());
if(strInput == strTemp)
{
cout << "yes" << "\n";
}
else
{
cout << "no" << "\n";
}
}
return 0;
}
2. ์ถ๊ฐ ํ์ด 1 (ํฌ ํฌ์ธํฐ)
- ์๊ณ ๋ฆฌ์ฆ
Two Pointer
- ์ค๋ช
ํฌ ํฌ์ธํฐ ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํ ํฐ๋ฆฐ๋๋กฌ ๋ฌธ์ ์ ๊ฐ์ฅ ์ ์์ ์ธ ํ์ด์ด๋ค.
๋ง์ด ํ์ ์๋ ํฐ๋ฆฐ๋๋กฌ ๋ฌธ์ ์์ ๊ฐ์ฅ ๋ง์ด ๋ณด์ด๋ ํ์ด์ด๋ค. reverse๋ ์ฌ์ฉํ์ง ์๊ธฐ ๋๋ฌธ์ <algorithm> ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ ํ์๊ฐ ์๋ค.
์๊ฐ ๋ณต์ก๋๋ ๋ฌธ์์ด ๊ธธ์ด์ ๋น๋กํ๊ธฐ ๋๋ฌธ์ O(N)์ด๋ค.
- ์ฝ๋
์ถ๊ฐ ํ์ด ์ฝ๋
#include <iostream>
#include <string>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
while(true)
{
int iInput{};
cin >> iInput;
if(iInput == 0)
{
break;
}
string strInput{ to_string(iInput) };
bool bPalin{ true }; // ํฐ๋ฆฐ๋๋กฌ์ธ์ง ์ค์๊ฐ์ผ๋ก ์ถ์ ํ๋ flag ๋ณ์
for(int iLeft = 0, iRight = static_cast<int>(strInput.length()) - 1; iLeft < iRight; ++iLeft, --iRight)
{
if(strInput[iLeft] != strInput[iRight]) // ๋ค๋ฅด๋ฉด ๋ฐ๋ก break;
{
bPalin = false;
break;
}
}
cout << (bPalin ? "yes" : "no") << "\n";
}
return 0;
}
3. ์ถ๊ฐ ํ์ด 2 (์ ์ ์ฐ์ฐ)
- ์๊ณ ๋ฆฌ์ฆ
Mathematics
- ์ค๋ช
string ์์ด ์ ์ ์ฐ์ฐ๋ง์ผ๋ก ํด๊ฒฐํ๋ ํ์ด์ด๋ค.
์
๋ ฅ์ด ์ ์ํ์ผ๋ก ๋ค์ด์ค๊ธฐ ๋๋ฌธ์, ๊ตณ์ด string์ผ๋ก ๋ณํํ๊ธฐ๋ณด๋ค ์
๋ ฅ๋ฐ์ ์ ์๋ฅผ ์๋ฆฟ์๋ง๋ค ๋ณํ ์ฐ์ฐ์ ํตํด ์์ ๋ค์ง์ด์ฃผ๋ ๋ฐฉ์์ด๋ค.
๋ฐฉ๋ฒ์ด ๋ ํนํด์ ์ด ๋ฌธ์ ๋ฅผ ํฌ์คํ ํ ์ด์ ์ด๊ธฐ๋ ํ๋ค. ํ์ง๋ง ์์ ๋ ํ์ด๊ฐ ๋ ์ง๊ด์ ์ด๋ฏ๋ก ๊ทธ๋ฆฌ ์ถ์ฒํ ๋งํ ํ์ด๋ ์๋ ๋ฏํ๋ค.
์ ์ ์๋ฆฟ์๋งํผ ๋ฐ๋ณตํ๋ฏ๋ก ์๊ฐ ๋ณต์ก๋๋ O(N)์ด๋ค.
- ์ฝ๋
์ถ๊ฐ ํ์ด ์ฝ๋
#include <iostream>
#include <string>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
while(true)
{
int iInput{};
cin >> iInput;
if(iInput == 0)
{
break;
}
int iOrigin{ iInput }, iReverse{};
// iReverse์๋ iInput์ 1์ ์๋ฆฌ๋ฅผ ๋ํ ๋ค 10์ ๊ณฑํ๊ณ iInput์ 10์ ๋๋ ์ฃผ๋ ์ฐ์ฐ์ ๋ฐ๋ณต
while(iInput > 0)
{
iReverse = iReverse * 10 + iInput % 10;
iInput /= 10;
}
if(iOrigin == iReverse)
{
cout << "yes\n";
}
else
{
cout << "no\n";
}
}
return 0;
}
๐ญ ํ๊ธฐ
๊ฐ์ฅ ๊ธฐ๋ณธ์ ์ธ ํํ์ ํฐ๋ฆฐ๋๋กฌ ๋ฌธ์ ๊ฐ ์๋๊น ์ถ๋ค.
ํฌ ํฌ์ธํฐ ์๊ณ ๋ฆฌ์ฆ์ ์ด๋ฌํ ์ ํ์ ๋ฌธ์ ์์ ์ ๋ง ์์ฃผ ์ฐ์ด๋ ์๊ณ ๋ฆฌ์ฆ์ด๊ณ , ์ ์ ๋ณํ ํ์ด๋ โ์ด๋ฐ ํ์ด๋ ์๊ตฌ๋โ ํ๊ณ ๋ด๋๋ฉด ์ข์ ๊ฒ ๊ฐ๋ค.
Comments