2017年7月7日 星期五

Roman to Integer

The submission can not too complex.
var RomanNumber = map[rune]int {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500, 
    'M': 1000,
}

func romanToInt(s string) int {
    r := []rune(s)
    result := 0
    for i :=0; i<len(r); i++ {  
        if i>0 && RomanNumber[r[i]] > RomanNumber[r[i-1]] {  
            result += RomanNumber[r[i]] - 2*RomanNumber[r[i-1]]
        } else {
            result += RomanNumber[r[i]]
        }  
    }  
    return result
}
Overview this solution. It just use a map to looking for number.
The only thing need explanation is 
if i>0 && RomanNumber[r[i]] > RomanNumber[r[i-1]] {  
    result += RomanNumber[r[i]] - 2*RomanNumber[r[i-1]]
}
Take a example
Roman: IV r[0] = I = 1, r[1] = V = 5
We know that is 4, 5 - 1. Ok, why -2*1? Because we need to remove prev round side effect.
overhead r[0] = I = 1 -> r[1] = V = 5
state          0 += 1 = 1 ->  1 += 5 - 2*1 = 4

That's all.
          

沒有留言:

張貼留言