LeetCode 13. Roman to Integer

本文介绍了一种将罗马数字转换为整数的算法实现。通过解析罗马数字的构成规律,该算法能正确处理从1到3999范围内的罗马数字。对于连续递增的罗马数字采用减法原则,反之则进行加法运算。

Given a roman numeral, convert it to an integer.

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

Subscribe to see which companies asked this question.

和上一篇文章相反,这个题是把罗马数字转换成阿拉伯数字,罗马数字十分好处理,如果两个数字是降序的,即可正常相加;

如果两个数字是升序的,那么代表要用大的数字减去小的数字。

public class Solution {
    public int romanToInt(String s) {
        int len = s.length();
        int []num = new int[len];
        int ans = 0;
        for(int i=0;i<len;i++){
            if(s.charAt(i)=='I'){
                num[i] = 1;
            }
            else if(s.charAt(i)=='V'){
                num[i] = 5;
            }
            else if(s.charAt(i)=='X'){
                num[i] = 10;
            }
            else if(s.charAt(i)=='L'){
                num[i] = 50;
            }
            else if(s.charAt(i)=='C'){
                num[i] = 100;
            }
            else if(s.charAt(i)=='D'){
                num[i] = 500;
            }
            else if(s.charAt(i)=='M'){
                num[i] = 1000;
            }
        }
        for(int j=0;j<len;j++){
            if(j!=len-1&&num[j]<num[j+1]){
                ans += (num[j+1]-num[j]);
                j++;
            }
            else ans += num[j];
        }
        return ans;
    }
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值