# 【前端问题精选】从下面一个列表 `(x, y)` 构造一个函数 `y = f(x)`

1. `[1, 5, 10, 50, 100, 500, 1000]`
2. `'IVXLCDM'`

• `f(1); // 'I'`
• `f(2); // 'II'`
• `// ...`
• `f(6); // 'VI'`
• `f(7); // 'VII'`
• `// ...`
• `f(800); // 'DCCC'`
• `f(900); // 'CM'`

### 回答：

``````function num2roman(nVal,nMode )
{
var pChars = ['M','D','C','L','X','V','I'];
var pValues = [1000,500,100,50,10,5,1];
var nMaxIndex = pValues.length-1;
var aRoman = "";
for(var i=0 ; i<= Math.floor( nMaxIndex/2 ); i++)
{
var nIndex = 2 * i;
var nDigit = Math.floor( nVal/pValues[nIndex] );
if((nDigit%5)==4)
{
var nIndex2 = (nDigit == 4) ? nIndex - 1 : nIndex - 2;
var nSteps = 0;
while( (nSteps < nMode) && (nIndex < nMaxIndex) )
{
nSteps++;
if( pValues[ nIndex2 ] - pValues[ nIndex + 1 ] <= nVal )
nIndex++;
else
nSteps = nMode;
}
aRoman += pChars[ nIndex ];
aRoman += pChars[ nIndex2 ];
nVal = nVal + pValues[ nIndex ];
nVal = nVal - pValues[ nIndex2 ];
}
else
{
if( nDigit > 4 )
aRoman += pChars[ nIndex - 1 ];
for(var j=0 ; j<(nDigit % 5) ; j++)
aRoman += pChars[ nIndex ];
nVal %= pValues[ nIndex ];
}
}
return aRoman;
}``````

### 回答：

``````const f = (num) => {
const Y = 'IVXLCDM';
const X = [1, 5, 10, 50, 100, 500, 1000];
const i = X.findIndex(value => value >= num);
if (X[i] === num) return Y.charAt(i);
const p = i - 2 + i % 2;
if (X[i] - X[p] === num) {
return Y.charAt(p) + Y.charAt(i);
}
let result = i % 2 ? '' : Y.charAt(i - 1);
if (result) num -= X[i - 1];
while (num > 0) {
result += Y.charAt(p);
num -= X[p];
}
return result;
};``````