SW Expert Academy
(SWEA c++)3750. Digit sum
naeunchan
2020. 11. 9. 13:13
728x90
반응형
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
long long 형으로 최대 10^18인 num을 입력 받는다.
num의 자리수가 한 자릿수가 될 때까지 while문으로 반복.
ans는 각 자릿수를 더한 값을 나타내므로, 이 역시 num을 10으로 나눴을 때 한 자릿수가 될 때까지 더해준다.
두 while문이 반복해서 끝나면 최종적으로 num에는 각 자릿수를 다 더하여 한 자릿수가 될 때까지의 결과값이 나오게 된다.
#include <cstdio>
#include <string>
using namespace std;
int main(void)
{
int t;
scanf("%d", &t);
for(int tc = 1; tc <= t; tc++)
{
long long ans, num;
scanf("%lld", &num);
while(num > 9)
{
ans = 0;
while(num > 9)
{
ans += num % 10;
num /= 10;
}
num += ans;
}
printf("#%d %lld\n", tc, num);
}
return 0;
}
728x90
반응형