码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-medium-Roman to Integer

时间:2016-04-05 12:27:59      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5354257.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!