c语言罗马数字转十进制,把罗马数字转为十进制 #JS_codewar_9

题目

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;

}

我的感想

看别人的代码,发现不用去在意遍历时,如果i+1超出了范围会怎么样,反正一样是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

)

}

我的感想

暂时没看明白……

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值