13. Roman to Integer

来源:互联网 发布:淘宝下载器 编辑:程序博客网 时间:2024/05/22 17:25

Given a roman numeral, convert it to an integer.

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

public class Solution {public int romanToInt(String s) {if(s == null || s.length() == 0){return 0;}int before = charToInt(s.charAt(s.length()-1));int sum = before;for(int i = s.length()-2; i >= 0; i--){int after = charToInt(s.charAt(i));if(before <= after){sum += after;}else {sum -= after;}before = after;}return sum;}       //before和after分别表示先读取的数字和后读取的数字,寻找罗马数字的规律,如果before小于等于after,正常加,否则要减。      public int charToInt(char roman){switch(roman){case 'I': return 1;case 'V': return 5;case 'X': return 10;case 'L': return 50;case 'C': return 100;case 'D': return 500;case 'M': return 1000;}return 0;        //遇到这种问题肯定是要新建一个方法通过罗马数字返回数值        }}
罗马数字从不会到会23333

0 0
原创粉丝点击