LeetCode.13 罗马数字转整数

题目链接:罗马数字转整数

分析:

如图示意:

例如,我们给定一个罗马字母 CXCI,其对应的真实数字应该为191

在编程的时候,把每个字母逐个解析的话,是这样:C + X + C + I = 100 + 10 + 100 + 1 = 211

这样结果就不对了,应该是再减去差值,也就是20,才可以到的真实的值 191

所以说,在我们对给定的字符串遍历的时候,去逐个解析,遇到上述 IV、IX、XL、XC、CD、CM 的时候

都应该在最后遍历的结果后,减去差值,最终才可以得到真实的转换后的数值

代码实现:

public class Solution {
    public int romanToInt(String input) {
        if (input == null || input.length() == 0)
            return 0;
        int result = 0;
        if (input.indexOf("CM") != -1)
            result -= 200;
        if (input.indexOf("CD") != -1)
            result -= 200;
        if (input.indexOf("XC") != -1)
            result -= 20;
        if (input.indexOf("XL") != -1)
            result -= 20;
        if (input.indexOf("IX") != -1)
            result -= 2;
        if (input.indexOf("IV") != -1)
            result -= 2;
        for (char c : input.toCharArray()) {
            if (c == 'M')
                result += 1000;
            else if (c == 'D')
                result += 500;
            else if (c == 'C')
                result += 100;
            else if (c == 'L')
                result += 50;
            else if (c == 'X')
                result += 10;
            else if (c == 'V')
                result += 5;
            else if (c == 'I')
                result += 1;
        }
        return result;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值