【Leetcode】:13. Roman to Integer 问题 in JAVA

35 篇文章 0 订阅

Given a roman numeral, convert it to an integer.

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

题目要求把罗马数字转换为阿拉伯数字,这个题很简单,只不过代码量比较大

先查查维基百科罗马数字的知识,各个字母分别代表什么意思

Symbol Value
I1
V5
X10
L50
C100
D500
M1,000

  • I placed before V or X indicates one less, so four is IV (one less than five) and nine is IX (one less than ten)
  • X placed before L or C indicates ten less, so forty is XL (ten less than fifty) and ninety is XC (ten less than a hundred)
  • C placed before D or M indicates a hundred less, so four hundred is CD (a hundred less than five hundred) and nine hundred is CM (a hundred less than a thousand)[5]
另外存在一些特例,比如IV=4,IX=9,XL=40,XC=90,CD=400,CM=900;

------------------------------------------------------------------------------------------------------------------------------------------------------------------------

public class Solution {
    public int romanToInt(String s) {
        int num = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'C') {
                if ((i + 1 < s.length()) && s.charAt(i + 1) == 'M') {
                    num += 900;
                    i++;
                } else if ((i + 1 < s.length()) && s.charAt(i + 1) == 'D') {
                    num += 400;
                    i++;
                } else {
                    num += 100;
                }
            } else if (s.charAt(i) == 'X') {
                if ((i + 1 < s.length()) && s.charAt(i + 1) == 'C') {
                    num += 90;
                    i++;
                } else if ((i + 1 < s.length()) && s.charAt(i + 1) == 'L') {
                    num += 40;
                    i++;
                } else {
                    num += 10;
                }
            } else if (s.charAt(i) == 'I') {
                if((i + 1 < s.length()) && s.charAt(i + 1) == 'X') {
                    num += 9;
                    i++;
                } else if ((i + 1 < s.length()) && s.charAt(i + 1) == 'V') {
                    num += 4;
                    i++;
                } else {
                    num += 1;
                }
            } else if (s.charAt(i) == 'M') {
                num += 1000;
            } else if (s.charAt(i) == 'D') {
                num += 500;
            } else if (s.charAt(i) == 'L') {
                num += 50;
            } else if (s.charAt(i) == 'V') {
                num += 5;
            }
        }
        return num;
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值