LeetCode | Integer to Roman(整數轉換成羅馬數字)
阿新 • • 發佈:2019-01-06
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
關於羅馬數字的詳細表示:羅馬數字詳解
但是並沒有連結中表示的那麼複雜,羅馬數字只有1,5,10,50,100,500,1000(I,V,X,L,C,D,M)這幾個數字,因此,我們可以從大到小遍歷,比如2345,2000>1000,得到一個'M',然後變成1345,同樣,再減1000,得到"MM",變成345,依次類推即可。
但是對於4,9,40,90,900表示的時候並不是符合規律的表示,其分別為IV,IX,XL,XC等等……
然後再參照是航母的,大於1000時,我們減去1000,並得到一個M以此類推,就能得到想要的結果。
#include <stdio.h> #include <stdlib.h> #include <string.h> void IntegerToRoman(int n); int main() { int n; while(scanf("%d",&n) == 1){ IntegerToRoman(n); } return 0; } void IntegerToRoman(int n) { if(n < 1 || n > 3999) return; int value[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1}; char *roman[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; char store[20] = {0}; int len = sizeof(value)/sizeof(int); for(int i = 0;i < len;++i){ while(n >= value[i]){ n -= value[i]; strcat(store,roman[i]); } } printf("%s\n",store); }