1. 程式人生 > >C語言——整數轉化成羅馬數字

C語言——整數轉化成羅馬數字

計蒜客——整數轉化為羅馬數字的一點體會:

首先想到的思路是單獨一個一個的把輸入的數字拆分開來,每一位對應的數字轉化成羅馬數字,建立{由於題目限制}(1-3999)四個陣列分別代表unit、ten、hundred、thousands四個陣列分別內部表示1-9每個數字,

    char* String_thousand[3]={"M","MM","MMM"};
    char* String_hundred[9]={"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
    char* String_ten[9]={"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
    char* String_unit[9]={"I","II","III","IV","V","VI","VII","VIII","IX"};
    char* String_Temp=NULL;

然後就是將輸入的數字拆分分別對應

    thousand=num/1000;
    hundred=num/100-10*(num/1000);
    ten=num/10-10*(num/100);
    unit=num%1000%100%10;

然後進行每位數字的判斷。

其網上最優解法是用了一個二維陣列代替

static char *roman[][10]={"","I","II","III","IV","V","VI","VII","VIII","IX",

"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC",

"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM",

"","M","MM","MMM"};

然後通過一個for迴圈解決分離每一位的問題

  1. for(j = 0, i = 10000; j < 4; ++j, i/=10)

  2. {

  3. n = (num%i) / (i/10);

  4. printf("%s",roman[3-j][n]);

  5. }