当前位置:网站首页>13. Roman numeral to integer

13. Roman numeral to integer

2022-06-22 23:39:00 Front end plasterer

Roman numerals contain the following seven characters : I, V, X, L,C,D and M.

	 character            The number 
	I             1
	V             5
	X             10
	L             50
	C             100
	D             500
	M             1000

for example , Rome digital 2 Write to do II , Two parallel 1.12 Write to do XII , That is to say X + II . 27 Write to do XXVII, That is to say XX + V + II .

Usually , The small numbers in roman numbers are to the right of the big ones . But there are special cases , for example 4 Do not write IIII, It is IV. Numbers 1 In number 5 Left side , The number represented is equal to the large number 5 Decimal reduction 1 Value obtained 4 . similarly , Numbers 9 Expressed as IX. This special rule only applies to the following six cases :

I Can be placed in V (5) and X (10) Left side , To express 4 and 9.
X Can be placed in L (50) and C (100) Left side , To express 40 and 90.
C Can be placed in D (500) and M (1000) Left side , To express 400 and 900
Method 1:

function romanToInt(s) {
    
    let map = {
    
        "I": 1,
        "V": 5,
        "X": 10,
        "L": 50,
        "C": 100,
        "D": 500,
        "M": 1000,
    }
    let result = 0;
    for (let i = 0; i < s.length; i++) {
    
        if(map[s[i]] < map[s[i+1]]){
    
            result -= map[s[i]]
        }else{
    
            result += map[s[i]]
        }
    }
    return result;
};
原网站

版权声明
本文为[Front end plasterer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222051389568.html