본문 바로가기

Algorithm

(C++) - 백준(BOJ) 2231번 : 분해합

반응형
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//생성자의 각 자리수 + 생성자(M) = 분해합(N)
//생성자의 각 자리수를 계속 분해합에 빼고 1씩 더한다.
#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
using namespace std;
string int2str(int n)
{
    stringstream ss; // create a stringstream
    ss << n; // add n to the stream
    return ss.str();
}
 
int main() {
    int ans=0,tmp = 0;
    int i;
    string n,m = "0";//n는 분해합 m는 생성자
    cin >> n;
    int Nnum = stoi(n);//분해합
    for(int i = 0; i<=Nnum; i++)
    {
        tmp = 0;
        for (int j = 0; j < m.length(); j++)
        {
            tmp += m[j]-'0';
        }
        tmp += stoi(m);
        if (tmp == Nnum) { ans = 1break; }
        int Mnum = stoi(m);
        m = int2str(Mnum + 1); //문자로 변환
        
    }
    if (ans == 1)
        cout << m << '\n';
    else
        cout << "0" << '\n';
}
cs