13.Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

Analyse:

//• I 代表 1

//• V 代表 5

//• X 代表 10

//• L 代表 50

//• C 代表 100

//• D 代表 500

//• M 代表 1000

/*ex:

I -> 1

II -> 2

III -> 3

// 但這種會比較特殊

IV -> 4

// 當小數字在大數字的前面時,變成大數字減小數字

// 繼續下去

V -> 5

VI -> 6

VII -> 7

VIII -> 8

// 又遇到一個,所以是 10 - 1

IX -> 9

/* ex:

例如 XLIX ->

X -> 答案 = 10

// L 符合規則二 (L > X)

L -> 答案 = 10 + (50 - 2*10)

I -> 答案 = 10 + 30 + 1

// X 符合規則二 (X > I)

X -> 答案 = 10 + 30 + 1 + (10 - 2*1)

-> 答案 = 10 + 30 + 1 + 8 = 49

*/

Solution:

class Solution {

    func romanToInt(_ s: String) -> Int {
        let dictionary:[Character: Int] = ["I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000];

        let chars = Array(s);
        var output = 0;

        if(chars.count == 0) {
            return 0;
        }

        output = dictionary[chars[0]]!

        for i in 1..<chars.count {
            let char = chars[i];
            let value = dictionary[char]!

            let pchar =  chars[i - 1];
            let bvalue = dictionary[pchar]!

            output = output + value;

            if(value > bvalue) {
                output = output - 2 * bvalue;
            }
        }
        return output;
    }
}

results matching ""

    No results matching ""