leetcode 13. Roman To Integer

//Given a roman numeral, convert it to an integer.

//Input is guaranteed to be within the range from 1 to 3999.
 
//【罗马数字】
//1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};
//10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};
//100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};
//1000~3000: {"M", "MM", "MMM"}.


public class Solution {
	
	public static void main(String[] args) {
		String a = "MMMXL";
		int result = romanToInt(a);
		System.out.println(result);
	}
	
	public static int romanToInt(String s) {
		int result = 0;
		int a = 0;
		int b = 0;
		if(s.charAt(0) == 'I'){						//根据不同的情况为a赋值
    		a = 1;
    	}else if(s.charAt(0) == 'V'){
    		a = 5;
    	}else if(s.charAt(0) == 'X'){
    		a = 10;
    	}else if(s.charAt(0) == 'L'){
    		a = 50;
    	}else if(s.charAt(0) == 'C'){
    		a = 100;
    	}else if(s.charAt(0) == 'D'){
    		a = 500;
    	}else if(s.charAt(0) == 'M'){
    		a = 1000;
    	}
		result = a;
        for(int i = 1;i<s.length();i++){
        	b = a;
        	if(s.charAt(i) == 'I'){
        		a = 1;
        	}else if(s.charAt(i) == 'V'){
        		a = 5;
        	}else if(s.charAt(i) == 'X'){
        		a = 10;
        	}else if(s.charAt(i) == 'L'){
        		a = 50;
        	}else if(s.charAt(i) == 'C'){
        		a = 100;
        	}else if(s.charAt(i) == 'D'){
        		a = 500;
        	}else if(s.charAt(i) == 'M'){
        		a = 1000;
        	}
        	result = result + a;					//对结果进行累加
        	if(b == a/5||b == a/10){				//当出现"IV","XL","CD","IX","XC","CM"时进行相应处理
        		result = result - 2*b;
        	}
        }
        return result;
    }
	
}


你可能感兴趣的:(LeetCode)