題目
Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral.
Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order.
Example:
solution('XXI'); // should return 21
我的代碼
function solution(roman){
// complete the solution by transforming the
// string roman numeral into an integer
let bucket = {"M":1000, "D":500, "C":100, "L":50, "X":10, "V":5, "I":1};
let roman_array = roman.split('').map(function(x){return bucket[x]});
console.log(roman_array);
for (i = 0; i < roman_array.length - 1; i++) {
if (roman_array[i] - roman_array[i+1] >= 0) {
roman_array[i] = "+" + roman_array[i];
} else {
roman_array[i] = "-" + roman_array[i];
}
}
roman_array[roman_array.length - 1] = "+" + roman_array[roman_array.length - 1];
console.log(roman_array);
let result = roman_array.reduce(function(acc, val){return acc*1 + val*1});
console.log(result);
return result;
}
別人的代碼
function solution(roman)
{
var data = {M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1};
var numbers = roman.split('');
var sum = 0, i;
for(i = 0; i < numbers.length; i++)
{
if(data[numbers[i]] < data[numbers[i+1]])
{
sum += data[numbers[i+1]] - data[numbers[i]];
i++;
}
else
{
sum += data[numbers[i]];
}
}
return sum;
}
我的感想
看別人的代碼前翎,發(fā)現(xiàn)不用去在意遍歷時(shí)缚忧,如果i+1超出了范圍會(huì)怎么樣,反正一樣是false
把唯一的情況(相減)香到,寫成if,其余都被包含在else里了。
別人的代碼2
function solution(roman){
var rom ={ "I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000};
return roman.split('').reverse().reduce(
function(dec,c,i,rr){
c=rom[c];
i=rom[rr[i-1]]||0;
return dec + (i<=c? c: -c) }
,0
)
}
我的感想
暫時(shí)沒看明白……