力扣13. 罗马数字转整数

本文提供了一种将罗马数字转换为整数的方法。通过分析特定组合(如IV、IX等)并利用indexOf方法查找这些组合的存在与否来调整最终结果。此外,还遍历字符串中的每个字符以累加其对应的数值。
class Solution {
    public int romanToInt(String s) {
        if(s == null || s.length() == 0) return 0;
        int result = 0;
        if(s.indexOf("IV") != -1) result -= 2;//没有该元素的时候才返回-1
        if(s.indexOf("IX") != -1) result -= 2;
        if(s.indexOf("XL") != -1) result -= 20;
        if(s.indexOf("XC") != -1) result -= 20;
        if(s.indexOf("CD") != -1) result -= 200;
        if(s.indexOf("CM") != -1) result -= 200;
        char[] c = s.toCharArray();
        for(int i = 0; i < c.length; i++){
            if(c[i] == 'I') result += 1;
            else if(c[i] =='V') result += 5;
            else if(c[i] =='X') result += 10;
            else if(c[i] =='L') result += 50;
            else if(c[i] =='C') result += 100;
            else if(c[i] =='D') result += 500;
            else if(c[i] =='M') result += 1000;
        }
        return result;
    }
}

归纳:
indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1,特殊的是,罗马数字表示的IV、IX等只会出现一次

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值