[lintcode medium]Roman to Integer

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

Clarification

What is Roman Numeral?

 

public class Solution {
    /**
     * @param s Roman representation
     * @return an integer
     */
    public int romanToInt(String s) {
        // Write your code here
        
        int ret=0;
        
        for(int i=0;i<s.length();i++)
        {
            if(i+1==s.length())
            {
                ret+=toNumber(s.charAt(i));
            }
            else
            {
               if(toNumber(s.charAt(i))<toNumber(s.charAt(i+1)))
               {
                  ret+=toNumber(s.charAt(i+1))-toNumber(s.charAt(i));
                  i++;
               }
               else    
               {
                  ret+=toNumber(s.charAt(i));
               }
            }
        }
        
        
        return ret;
    }
    
    public int toNumber(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;
    }
}

 

posted on 2016-01-05 06:53  一心一念  阅读(140)  评论(0编辑  收藏  举报

导航