각 자리수의 숫자를 더해주고, 더해진 숫자가 1자리면 출력하고 아니라면 반복한다.


최대 1000자리의 숫자가 입력이 되니 BigInteger가 아니면 처리를 문자열로 해야된다.


그래서 생각해보니 1000 * 9 = 9000

최대 나올 수 있는 숫자가 9000이여서

문자열을 다 더해주고 하나하나 나눠주고 다 했다.

#include <cstdio>
/**
* https://www.acmicpc.net/problem/6378
* BOJ 백준온라인져지 6378 디지털 루트 풀이
*/
int main(){
char N;
int result = 0, temp = 0;
while(1){
scanf("%c", &N);
if(N == '0' && result == 0) break;
if(N <= '9' && N >= '0'){
result += N - 48;
}else{
while(result >= 10){
if(result >= 1000) temp += result / 1000, result -= result / 1000 * 1000;
if(result >= 100) temp += result / 100, result -= result / 100 * 100;
if(result >= 10) temp += result / 10, result -= result / 10 * 10;
result %= 10;
result += temp;
temp = 0;
}
printf("%d\n", result);
temp = result = 0;
}
}
}
view raw BOJ_6378.cpp hosted with ❤ by GitHub


+ Recent posts