[백준 6378] 디지털 루트 (C#, C++) - soo:bak
작성일 :
문제 링크
설명
주어진 수의 자릿수를 반복해서 더해 한 자리가 될 때까지 구하는 디지털 루트 문제입니다.
접근법
문자열로 입력을 받아 각 자릿수를 더합니다.
결과가 10 이상이면 다시 자릿수를 더하는 과정을 반복합니다.
한 자리가 되면 그 값을 출력하고, 0이 입력되면 종료합니다.
Code
C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
class Program {
static void Main() {
while (true) {
var s = Console.ReadLine()!;
if (s == "0") break;
var val = 0;
var cur = s;
while (true) {
val = 0;
foreach (var c in cur)
val += c - '0';
if (val < 10) break;
cur = val.ToString();
}
Console.WriteLine(val);
}
}
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
string s;
while (cin >> s && s != "0") {
string cur = s;
int val = 0;
while (true) {
val = 0;
for (char c : cur)
val += c - '0';
if (val < 10) break;
cur = to_string(val);
}
cout << val << "\n";
}
return 0;
}