Day 2: Buckle 13 questions, Roman numerals to whole numbers:
Address: leetcode-cn.com/problems/ro…
Here’s the idea: The Roman numeral does not require a judgment on the format of the input, which saves a lot of work.
Roman numeral turns integer to have two kinds of circumstance only, one kind is small numeral is in front of big numeral, want to subtract namely, make one kind is normal add went, so want to make a judgment only ok.
var romanToInt = function(s) {
let object = {
‘I’:1,
‘V’:5,
‘X’:10,
‘L’:50,
‘C’:100,
‘D’:500,
‘M’:1000,
}; // Define object;
let sum = 0; // declare a variable to hold the return value
let a = s.split(“”); // Declare a as an array and store s as an array in A
for(let i = 0; i < a.length; i++)
{
If (object[a[I]]<object[a[I +1]]
{
sum = sum – object[a[i]]+object[a[i+1]];
i++;
}
else{
sum = sum + object[a[i]];
}// The second case
}
return sum;
};
Execution time: 172 ms, beating 73.54% of all JavaScript commits