leetcode 13. Roman to Integer

来源:互联网 发布:mac os x office 编辑:程序博客网 时间:2024/05/21 12:24

Given a roman numeral, convert it to an integer.

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

与leetcode 12题相反,将罗马数字转换成阿拉伯数字(小于3999)

从前向后遍历如果前面的比后面的小,则加上后面减去前面的值,指针向后移动一位,反之,加上前面的值.

public class A13RomantoInteger {public int romanToInt(String s) {int ans = 0;for(int i = 0; i < s.length(); i++) {int m = valueOfRoman(s.charAt(i));if(i + 1 < s.length() && m < valueOfRoman(s.charAt(i + 1))) {ans += valueOfRoman(s.charAt(i + 1)) - m;i++;} else {ans += m;}}        return ans;    }// I(1),V(5),X(10),L(50),C(100),D(500),M(1000)public int valueOfRoman(char c) {switch(c) {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;}}


0 0
原创粉丝点击