天天看點

計蒜客——整數轉換成羅馬數字

1000ms 65536K

給定一個整數 numnum,将整數轉換成羅馬數字。

如 1,2,3,4,51,2,3,4,5 對應的羅馬數字分别為I,II,III,IV,V等,更詳細的說明見此 連結。

輸入格式

第一行輸入一個整數 num(1 \leq num \leq 3999)num(1≤num≤3999)。

輸出格式

輸出 numnum 對應的羅馬數字。

樣例輸入

123

樣例輸出

CXXIII

#include<stdio.h>
#include<malloc.h>
#define N 30
int thousand,hunderd,ten,one,i = 0,j = 0;
char* str;
char Roma[8] = {'I','V','X','L','C','D','M'};
char* calculate(int X);
void SpecialCalculate(int num,int flag);
int main(void)
{
    int num;
	str = (char*)malloc(sizeof(char)*N);
    scanf("%d",&num);
    printf("%s",calculate(num));
    return 0;
}
char* calculate(int X)
{
    
    thousand = X/1000;
    hunderd = X%1000/100;
    ten = X%100/10;
    one = X%10;
    //處理千位數
    if(thousand != 0)
        for(j = 0;j < thousand;j++)
            str[i++] = Roma[6];
    if(hunderd != 0)
    {
        //3以下的直接循環輸出  4則特别輸出,5到8循環輸出,9特殊
        SpecialCalculate(hunderd,0);
    }
    if(ten != 0)
    {
        SpecialCalculate(ten,1);
    }
    if(one != 0)
        SpecialCalculate(one,2);
    str[i] = '\0';
	return str;
}
void SpecialCalculate(int num,int flag)
{
    int gap = flag*2;
    if(num <= 3)
            for(j = 0;j < num;j++)
                str[i++] = Roma[4-gap];
        else if(4 == num)
        {
            str[i++] = Roma[4-gap];
            str[i++] = Roma[5-gap];
        }
        else if(9 == num)
        {         
            str[i++] = Roma[4-gap];
            str[i++] = Roma[6-gap];
        }
        else
        {
            str[i++] = Roma[5-gap];
            for(j = 0;j<num - 5;j++)
                str[i++] = Roma[4-gap];
        }
}
           

繼續閱讀