leetcode-Easy-第5期-Roman to Integ
2019-02-27 本文已影响4人
石头说钱
题目:Roman to Integer
- 例子
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
- Example 1:
Input: "III"
Output: 3
- Example 2:
Input: "IV"
Output: 4 // V-I = 5-1=4
- Example 3:
Input: "IX"
Output: 9
Example 4:
- Example 4
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
- Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
const romantic = (value) => {
const obj = {
I:1,
V:5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
const arr = value.toUpperCase().split('')
const numberArr = arr.map(item => obj[item])
console.log(numberArr)
let count = 0
const len = numberArr.length
for(let i=0;i<len;i++){
console.log(i)
if( numberArr[i]<numberArr[i+1]){
// 出现左边比右边小,当前的加数应该大减小的值
count+=numberArr[i+1]-numberArr[i]
// 左边比右边小,累加的值是大的减小的,这个两项的值已经加进去了,
// 所以下一个累加的项是i+2
i = i+1 //这里 i+1,是因为,上面i++还会把i再次加1
}else {
count += numberArr[i]
}
}
return count
}
const res = romantic("MCMXCIV") //1994
分析
"MCMXCIV" 变成数组:
[1000,100,1000,10,100,1,5]
正常取值: 1000+100+1000+10+100+1+5
本题规则:
1 1000 > 100,count = 1000
2 100 < 1000,count = 1000 + (1000-100) = 1900 //
3 10 < 100, count = 1900 + (100-10) =1990
4 1 < 5, count = 1990 + (5-1) = 1994
//分析第2步原因,如果左边的值小于相邻右边的值,就不能直接将二者累加,而是只取大减小的差
//并且一次性消耗掉2个数值的值
// 因为第2为100小于第3位1000,所以本来应该 count + 100 + 1000
//变成了count + (1000-100) ,一次性消耗掉第2和第3位的数字,其余同理