본문 바로가기
카테고리 없음

SW 3750 Digit sum [D3]

by 문자메일 2018. 3. 26.

#include <stdio.h>

#include <math.h>


void init();


int T = 0;

unsigned long int N = 0; // 1 <= N <= 10^18

int sum = 0;

int cnt = 0; //자릿수


int main(void)

{

scanf(" %d", &T);

init();


//TestCase 수만큼 반복

for (int tc = 1; tc <= T; tc++){

init();

scanf(" %ld", &N);

//f(n) 함수

while (1){

unsigned long int tempN = N;

//입력받은 N의 자릿수 구해서 cnt에 저장.

while (1){

if ((tempN = tempN / 10) > 0) cnt++;

else break;

}


tempN = N;

for (int i = cnt; i >= 0; i--){

int index = pow(10.0, i);

sum += tempN / index; //몫은 더하고

tempN = tempN % index; // 나머지는 재연산 하기 위해 저장


//더이상 나눌 수 가 없으면 미리 break 

//ex) 150000 같은 경우;

if (tempN == 0) break;

}

//f(n) 값이 10 미만인 경우 출력하고 다음 TestCase 실행

if (sum < 10){ 

printf("#%d %d\n", tc, sum);

break;

}

//자릿수 전부 더한것이 10보다 커서 함수를 재 수행해야 한다면, 필요한것들 초기화

else{ N = sum; cnt = 0; sum = 0; }

}

}

return 0;

}


void init(){

N = 0; sum = 0; cnt = 0;

}

댓글