欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode—— 13. Roman to Integer

程序员文章站 2024-02-03 16:53:46
...

题目原址

https://leetcode.com/problems/roman-to-integer/description/

题目描述

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.

解题思路

罗马数字一共有7个字母

M D C L X V I
1000 500 100 50 10 5 1

1. 将字符串每个字符转换为对应罗马数字代表的整数
2. 按照罗马数字的组合规则,如果前面的字符小于后面字符的值,则用后面的数减去前面的数为该罗马数字的整数值;如果前面的字符大于后面字符的值,则用后面的数加上前面的数为该罗马数字的整数值。如IV的值为4,VI的值为6

AC代码

class Solution {
    public int romanToInt(String s) {
        int ret = 0;
        int[] a = new int[s.length()];
        for(int i = 0; i < s.length(); i++) {
            switch(s.charAt(i)) {
                case 'M':
                    a[i] = 1000;
                    break;
                case 'D':
                    a[i] = 500;
                    break;
                case 'C':
                    a[i] = 100;
                    break;
                case 'L':
                    a[i] = 50;
                    break;
                case 'X':
                    a[i] = 10;
                    break;
                case 'V':
                    a[i] = 5;
                    break;
                case 'I':
                    a[i] = 1;
                    break;
            }
        }

        for(int i = 0;i<s.length()-1;i++) {
            if(a[i] < a[i+1])
                ret -= a[i];
            else
                ret += a[i];
        }
        return ret + a[s.length()-1];
    }
}

感谢

https://leetcode.com/problems/roman-to-integer/discuss/6509/7ms-solution-in-Java.-easy-to-understand