[Programmers] Lv2. ์ซ์์ ํํ | C++
2023. 6. 12. 20:27ใCoding Test/Programmers
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐จ๐ปํ์ด ๊ณผ์
- for๋ฌธ์ ํตํด ์์ฐ์ 1๋ถํฐ ์ฐจ๋ก๋๋ก ํฉ๊ณ์ ๋ํ๊ณ , Queue์๋ ์์๋ฅผ ์ถ๊ฐํฉ๋๋ค.
- ๋ง์ฝ ํฉ๊ณ๊ฐ n๊ณผ ๊ฐ๋ค๋ฉด answer + 1๋ฅผ ํด์ฃผ๊ณ , n < ํฉ๊ณ๊ฐ ๋๋ ์ํฉ์ด๋ผ๋ฉด Queue์์ ํ๋์ฉ pop ํ์ฌ ํฉ๊ณ์์ ๋บ๋๋ค.
- Queue์ ์์๋ฅผ popํ์ฌ ๋บ ํฉ๊ณ๊ฐ n๊ณผ ๊ฐ๋ค๋ฉด answer + 1์ ํด ์ฃผ๊ณ , ์๋๋ผ๋ฉด ํ๊ฐ ๋น๊ฑฐ๋, ํฉ๊ณ < n์ด ๋๋ ์ํฉ๊น์ง ์งํํด์ค๋๋ค.
โ๏ธ์์ค ์ฝ๋ ๋ฐ ๊ฒฐ๊ณผ
#include <string>
#include <queue>
using namespace std;
int solution(int n) {
queue<int> myQueue;
int answer = 0;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
myQueue.push(i);
if (sum == n)
answer++;
else if (n < sum) {
while (!myQueue.empty()) {
int num = myQueue.front();
myQueue.pop();
sum -= num;
if (sum == n)
answer++;
else if (sum < n)
break;
}
}
}
return answer;
}
728x90
๋ฐ์ํ
'Coding Test > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Programmers] Lv2. ํผ๋ณด๋์น ์ | C++ (0) | 2023.06.12 |
---|---|
[Programmers] Lv2. ์ด์ง ๋ณํ ๋ฐ๋ณตํ๊ธฐ | C++ (0) | 2023.06.12 |
[Programmers] Lv2. ์ต์๊ฐ ๋ง๋ค๊ธฐ | C++ (1) | 2023.06.11 |
[Programmers] Lv2. JadenCase ๋ฌธ์์ด ๋ง๋ค๊ธฐ | C++ (0) | 2023.06.11 |
[Programmers] Lv2. ๊ฑฐ๋ฆฌ๋๊ธฐ ํ์ธํ๊ธฐ | C++ (0) | 2023.06.09 |