[BaekJoon 28702][๐ค1] FizzBuzz
โ ๋ฌธ์
๐ฏ ๋์ด๋
Bronze ๐ค1
๐ง ํ์ด
1. ๋ด ํ์ด (๋ฌธ์์ด + ์ํ)
- ์๊ณ ๋ฆฌ์ฆ
string,Mathematics
- ์ค๋ช
๋ฌธ์์ด์ ์ฌ์ฉํ ์ซ์ ํ๋ณ๋ก ํผ ๋ฐฉ์์ด๋ค.
3์ ๋ฐฐ์์ 5์ ๋ฐฐ์๋ฅผ ์ ์ธํ๊ณ ์ซ์๊ฐ ๋์จ๋ค๋ฉด, 3๊ฐ์ ์ถ๋ ฅ์ด ๋์์ ๋ ๋ฌด์กฐ๊ฑด ํ๋ ์ด์์ ์ ์๊ฐ ๋์ฌ ์ ๋ฐ์ ์๋ค.
์ด๋ฐ ๊ท์น์ ์ด์ฉํด์, ์
๋ ฅ์ ๋ํด ๊ฐ๊ฐ์ ์
๋ ฅ ๋ฌธ์์ด์ด ์ ์์ธ์ง ํ๋ณํ๋ ํจ์๋ฅผ ๋ง๋ค์ด์ ํด๊ฒฐํ๋ค.
๋ฌธ์์ด์ ์ ์ ํ๋ณํ๋ ๋ฐ๋ณต๋ฌธ๊ณผ ์
๋ ฅ ๋ฐ๋ณต๋ฌธ ๋ฐ์ ์์ผ๋ฏ๋ก ์ฌ์ค์ O(1)์ ์๊ฐ ๋ณต์ก๋์ด๋ค.
- ์ฝ๋
๋ด ํ์ด ์ฝ๋
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
// ๋ฌธ์์ด์ด ์ซ์์ธ์ง ํ๋ณํ๋ ํจ์
bool IsNumber(const string& strInput);
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
string arrStr[3]{};
for(int i = 0; i < 3; ++i)
{
cin >> arrStr[i];
}
int iVal{}, iIndex{};
for(int i = 0; i < 3; ++i)
{
if(IsNumber(arrStr[i]))
{
// ์ซ์ ์ฐพ์ผ๋ฉด iVal์ ์ ์ฅ, iIndex์ ์ธ๋ฑ์ค ์ ์ฅ
iVal = stoi(arrStr[i]);
iIndex = i;
}
}
// ๋ค์์ ์ฌ ์ซ์ ๊ณ์ฐ
int iNext{ iVal + 3 - iIndex };
// 3์ ๋ฐฐ์ && 5์ ๋ฐฐ์
if(iNext % 15 == 0)
{
cout << "FizzBuzz";
}
// 3์ ๋ฐฐ์
else if(iNext % 3 == 0)
{
cout << "Fizz";
}
// 5์ ๋ฐฐ์
else if(iNext % 5 == 0)
{
cout << "Buzz";
}
// ๋ ๋ค X
else
{
cout << iNext;
}
return 0;
}
bool IsNumber(const string& strInput)
{
for(const char ch : strInput)
{
// isdigit์ผ๋ก ๋ฌธ์๊ฐ ์ซ์์ธ์ง ํ๋ณ -> ๋ฌธ์ ๊ฒ์ฌ์ด๋ฏ๋ก ์์ ํ๊ฒ unsigned char๋ก ์บ์คํ
if(!isdigit(static_cast<unsigned char>(ch)))
{
return false;
}
}
// ๋น ๋ฌธ์์ด์ด๋ฉด false ๋ฆฌํด
return !strInput.empty();
}
๐ญ ํ๊ธฐ
์ฒ์์ ์ด๋ค ๋ณต์กํ ๊ท์น์ด ์์๊น ์๊ฐํ๋๋ฐ ์๊ฐ๋ณด๋ค ๊ฐ๋จํ๊ฒ ํ๋ ธ๋ค.
๊ทธ๋ฆฌ๊ณ ๋ฌธ์์ ์ซ์ ํ๋ณ์ ๋์์ฃผ๋ isdigit ํจ์๋ฅผ ์์๋๋ฉด ํธํ ๊ฒ ๊ฐ๋ค!
Comments