[LeetCode] 13. Roman to Integer

</br>


Given a roman numeral, convert it to an integer.

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


</br>

Solution

The rule for the conversion from roman numeral to integer is

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

And when smaller number is in front of a bigger number, then smaller number should be subtracted from the latter one.

Hence, we can first translate the roman numeral to normal integer number, and then apply the second rule we mentioned above to determine we should add or minus this particular number.

The code is shown as below.

Java

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

</br>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 2008年一个来自贵州偏远农村的小伙邹市明,凭借自己的努力获得了48公斤奥运金牌。自此,走进了大家的眼前! 201...
    走走看看121阅读 163评论 0 0
  • KVO Key-Value observing(KVC),键值观察,它提供一种机制,当被观察的对象的属性被修改后,...
    iOS_陈楠阅读 694评论 1 51
  • 有一句话说:女孩子是没有爱情的,谁对她好,她就跟谁走了。 还有一句话说:你爱的,你想的,你牵挂的,最终会输给对你好...
    洛小娅阅读 841评论 1 2
  • 从前有一个完美的家庭,家里有两个小女孩分别是:姐姐Aeny和妹妹Arny,她们的妈妈是一位女警察,非常厉害,破过很...
    菲菲公主_d442阅读 687评论 0 1
  • composer n.作家;作曲家;设计者Mozart is a great composer at his ti...
    Flannery阅读 456评论 0 0

友情链接更多精彩内容