leetcode [13] Roman to Integer 将

2016-05-22  本文已影响413人  努力努力再努力_姜姜

罗马数字的表示方式

I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000

罗马数字的计数方式:

代码思路:

此时需要注意,这个小的数在上一轮中,已经被加过,这一轮假如只减一次,一加一减相当于值没有变;所以这次要将小的数减两次

public class Solution {
    public int romanToInt(String s) {
        char[] num = s.toCharArray();
        int pre = charToInt(num[0]);
        int result = pre;
        int now = 0;
        for(int j = 1;j<s.length();j++)
        {
            now = charToInt(num[j]);
            if(pre >= now)
            {
                result += now; 
            }
            else
            {
                result = result +now - 2 * pre;
            }
            pre = now;
        }
        return result;
    }
    public int charToInt(char c)
    {
        int value = 0;
        switch(c)
        {
            case 'I':
                value = 1;
                break;
            case 'V':
                value = 5;
                break;
            case 'X':
                value = 10;
                break;
            case 'L':
                value = 50;
                break;
            case 'C':
                value = 100;
                break;
            case 'D':
                value = 500;
                break;
            case 'M':
                value = 1000;
                break;
        }
        return value;
    }
}
上一篇下一篇

猜你喜欢

热点阅读