[LeetCode]013. Roman to Integer

本文详细介绍了LeetCode上关于罗马数字转整数的问题,包括解析规则、关键点及Python实现,涵盖从基础到进阶的解决方案。

今天做题的时候发现leetcode改版了,编译提交后可以看到所有的test cases。

leetcode的作者还是位华人,相当给力!

Given a roman numeral, convert it to an integer.

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


Solution: 

The concept of roman numerals.

本解法的关键点在于特殊数字的表达(即相减: 9 = 10 -1; 90 = 100 -10; 40 = 50 -10. etc)只存在于2个字符之间。其余均为相加。



public class Solution {
    public int charToNum (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;
            default: return 0;
        }
    }
    public int romanToInt(String s) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(s==null || s.length() <= 0){
            return 0;
        }
        int result = 0;
        int pos = s.length() - 1;
        while(pos >= 0){
            if(pos-1 >= 0 && charToNum(s.charAt(pos)) > charToNum(s.charAt(pos-1))){
                result += charToNum(s.charAt(pos)) - charToNum(s.charAt(pos-1));
                pos -= 2;
            }else{
                result += charToNum(s.charAt(pos));
                pos--;
            }
        }
        return result;
    }
}

2015-04-15 update python solution:

class Solution:
    # @param s, a string
    # @return an integer
    def romanToInt(self, s):
        romanDict = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
        length = len(s)
        if length == 1:
            return romanDict[s]
        result = romanDict[s[0]]
        for i in range(1, length):
            if romanDict[s[i]] > romanDict[s[i-1]]:
                result = result - romanDict[s[i-1]] + (romanDict[s[i]] - romanDict[s[i-1]])
            else:
                result += romanDict[s[i]]
        return result

s = Solution()
print s.romanToInt('M') == 1000
print s.romanToInt('MMM') == 3000
print s.romanToInt('MMMXXX') == 3030
print s.romanToInt('MMMCMXCIX') == 3999
print s.romanToInt('MMMCMXCVIII') == 3998
print s.romanToInt('MI') == 1001
print s.romanToInt('MMMIII') == 3003
print s.romanToInt('IV') == 4
print s.romanToInt('MMIX') == 2009
print s.romanToInt('MMMCDXLIX') == 3449


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值