#13 LeetCode——Roman to Integer

本文介绍了一种将罗马数字转换为阿拉伯数字的方法,并提供了一个Java实现示例。该方法通过遍历输入的罗马数字字符串,根据罗马数字的构成规则进行转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将罗马字符转化为阿拉伯数字表示

注:
罗马数字表示:I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、 M(1000)

阿拉伯数字罗马数字
1I
4IV
5V
9IX
10X
50L
100V
500D
1000M

java代码如下

public class Solution {
    public int romanToInt(String s) {
        char[] nums = s.toCharArray();
        int result = 0;
        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };  
        for (int i = 0; i < nums.length; i++) 
        {   
            //1000
            if(nums[i] == 'M')
            {
                result += 1000;
            }

            //100
            if(nums[i] == 'C' && i + 1 < nums.length)
            {
                if(nums[i + 1] == 'M' || nums[i + 1] == 'D')
                {
                    result -= 100;
                }
                else
                {
                    result += 100;
                }
            }
            else if(nums[i] == 'C')
            {
                result += 100;
            }

            //500
            if(nums[i] == 'D')
            {
                result += 500;
            }

            //10
            if(nums[i] == 'X' && i + 1 < nums.length)
            {
                if(nums[i + 1] == 'C' || nums[i + 1] == 'L')
                {
                    result -= 10;
                }
                else
                {
                    result += 10;
                }
            }
            else if(nums[i] == 'X')
            {
                result += 10;
            }

            //50
            if(nums[i] == 'L')
            {
                result += 50;
            }

            //1
            if(nums[i] == 'I' && i + 1 < nums.length)
            {
                if(nums[i + 1] == 'X' || nums[i + 1] == 'V')
                {
                    result -= 1;
                }
                else
                {
                    result += 1;
                }
            }
            else if(nums[i] == 'I')
            {
                result += 1;
            }

            //5
            if(nums[i] == 'V')
            {
                result += 5;
            }
        } 
       return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值