구현(Implementation)

백준 2145번: 숫자 놀이

cepiloth 2018. 7. 19. 20:26
반응형

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


1. 문제

초등학생인 도겸이는 숫자를 좋아한다. 어느날 도겸이는 숫자 책을 보다가 간단한 놀이를 하나 생각해냈다. 숫자 놀이의 규칙은 다음과 같다.


주어진 숫자의 각 자릿수를 더한다.

결과가 한 자릿수가 될 때 까지 규칙1을 반복한다.

예를들어, 숫자 673에 규칙을 적용해보면 결과는 7이 된다 ; 6 + 7 + 3 = 16, 1 + 6 = 7 


도겸이는 당신과 함께 숫자놀이를 하고싶어한다. 도겸이가 주는 숫자들을 풀어보자.


2. 알고리즘

키워드 - 구현, 수학


3. 코드


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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <list>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <math.h>
 
using namespace std;
 
#define MAX_SIZE 100
#define INF 0x7fffffff
#define CENDL "\n"
#define ll long long
 
int solve(int d) {
    int sol = 0;
    while(d) {
        int cand = d % 10;
        sol += cand;
        d = d / 10;
    }
    return sol;
}
int main() {
 
    cin.tie(0);
    std::ios::sync_with_stdio(false);
 
    while(true) {
        int d; cin >> d;
 
        if (d==0) {
            break;
        }
 
        while(d>9) {
            int cand = solve(d);
            d = cand;
        }
        
        cout << d << CENDL;
    }
    return 0;
}
 
cs

반응형