lintcode-medium-Roman to Integer

Posted 哥布林工程师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Roman to Integer相关的知识,希望对你有一定的参考价值。

Given a roman numeral, convert it to an integer.

The answer is guaranteed to be within the range from 1 to 3999.

 

Example

IV -> 4

XII -> 12

XXI -> 21

XCIX -> 99

 

public class Solution {
    /**
     * @param s Roman representation
     * @return an integer
     */
    public int romanToInt(String s) {
        // Write your code here
        
        if(s == null || s.length() == 0)
            return 0;
        
        int result = 0;
        
        for(int i = 0; i < s.length() - 1; i++){
            if(getNum(s.charAt(i)) < getNum(s.charAt(i + 1)))
                result -= getNum(s.charAt(i));
            else
                result += getNum(s.charAt(i));
        }
        
        result += getNum(s.charAt(s.length() - 1));
        
        return result;
    }
    
    public int getNum(char c){
        switch(c){
            case ‘I‘:   return 1;
            case ‘V‘:   return 5;
            case ‘X‘:   return 10;
            case ‘L‘:   return 50;
            case ‘C‘:   return 100;
            case ‘D‘:   return 500;
            case ‘M‘:   return 1000;
        }
        
        return 0;
    }
    
}

 

以上是关于lintcode-medium-Roman to Integer的主要内容,如果未能解决你的问题,请参考以下文章

to_char()的用法

TO_CHAR 和 TO_DATE 给出不同的结果。如何使用 TO_DATE 实现 TO_CHAR 功能?

`respond_to?` 与 `respond_to_missing?`

start: Unable to connect to Upstart: Failed to connect to socket /com/ubuntu/upstart:

adapt to 用法

链表又去重