LeetCode 13. Roman to Integer

来源:互联网 发布:数控铣床四叶草的编程 编辑:程序博客网 时间:2024/05/22 21:17

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;    }}


0 0
原创粉丝点击