프로그래밍 갤러리에서 간단한 문제가 하나 올라오길래 오랜만에 C 코딩도 해볼 겸 풀어봤다.
문제 정의)
입력 : 1 2 3 10 11 12 13 19 199 200 201 202 300 305 499
출력 : 1-3, 10-13, 19, 199-202, 300, 305, 499.
연속된 숫자가 입력될 때 해당 숫자의 범위를 ‘-’ 로 이어주는 문제이다.
숫자 혹은 범위 간에는 ‘,’ 를 출력하고, 마지막 출력은 ‘.’ 이다.
입력 숫자는 1<=i<=500 이고, 입력 갯수는 1<=n<=500 이다.
내가 푼 답)
@ codepad 사이트에 입력한 코드
새로 들어오는 값이 마지막으로 들어온 값과 연속되는 값인지만 체크하면 문제가 될 만한 것은 없다.
나머지는 다 입출력의 문제…
#include <cstdio>
#include <cstdlib>
#include <cstring>
const char * DELIMETER = " ";
int main(void)
{
char pszInput[] = "1 2 3 10 11 12 13 19 199 200 201 202 300 305 499";
char * token = strtok(pszInput, DELIMETER);
bool bFirstNumber = true; // for check ',' print
bool bContinue = false; // for check continuous
int nLastNumber = -10; // Should not continue the first input
while( NULL != token )
{
int nCurrentNumber = atoi(token);
if( (nLastNumber + 1) == nCurrentNumber )
{
// continuous number
bContinue = true;
}
else
{
if( bContinue )
{
// print last
printf("-%d", nLastNumber);
bContinue = false;
}
if( bFirstNumber )
{
printf("%d", nCurrentNumber);
bFirstNumber = false;
}
else
printf(",%d", nCurrentNumber);
}
nLastNumber = nCurrentNumber;
token = strtok( NULL, DELIMETER );
}
printf(".");
return 0;
}
</cstring></cstdlib></cstdio> |