数字和罗马数字互转
localROMAN={{1000,"M"},{900,"CM"},{500,"D"},{400,"CD"},{100,"C"},{90,"XC"},{50,"L"},{40,"XL"},{10,"X"},{9,"IX"},{5,"V"},{4,"IV"},{1,"I"},}localVALUES={I=1,V=5,X=10,L=50,C=100,D=500,M=1000,}functionconvertRoman(value)iftype(value)=="number"thenassert(value>=1andvalue<=3999andvalue%1==0,"只支持 1 到 3999 的整数")localresult={}for_,iteminipairs(ROMAN)dolocalcount=math.floor(value/item[1])ifcount>0thenresult[#result+1]=string.rep(item[2],count)value=value%item[1]endendreturntable.concat(result)endlocaltext=string.upper(tostring(value))localtotal,i=0,1whilei<=#textdolocalcurrent=VALUES[text:sub(i,i)]localnextValue=VALUES[text:sub(i+1,i+1)]assert(current,"非法罗马数字")ifnextValueandcurrent<nextValuethentotal=total+nextValue-current i=i+2elsetotal=total+current i=i+1endendreturntotalend运行
convertRoman(1994)-- "MCMXCIV"convertRoman("XIV")-- 14