[백준 2145] 숫자 놀이 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
주어진 양의 정수에 대해 각 자릿수를 모두 더하고, 결과가 한 자리 수가 될 때까지 반복합니다.
입력은 여러 줄이며 0이 나오면 종료합니다.
접근법
먼저, 자릿수 합을 구하는 함수를 만듭니다. 수를 10으로 나눈 나머지를 더하고, 10으로 나누는 과정을 반복합니다.
다음으로, 현재 값이 10 이상인 동안 자릿수 합 함수를 반복 적용합니다. 한 자리 수가 되면 출력합니다.
Code
C#
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
using System;
namespace Solution {
class Program {
static int DigitSum(int n) {
var s = 0;
while (n > 0) {
s += n % 10;
n /= 10;
}
return s;
}
static void Main(string[] args) {
while (true) {
var n = int.Parse(Console.ReadLine()!);
if (n == 0)
break;
while (n >= 10)
n = DigitSum(n);
Console.WriteLine(n);
}
}
}
}
C++
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
#include <bits/stdc++.h>
using namespace std;
int digitSum(int n) {
int s = 0;
while (n > 0) {
s += n % 10;
n /= 10;
}
return s;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
while (cin >> n && n != 0) {
while (n >= 10)
n = digitSum(n);
cout << n << "\n";
}
return 0;
}