码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]Roman to Integer

时间:2014-07-03 16:45:05      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:blog   java   2014   for   算法   io   

题目:给定一串罗马数字,要求将罗马数字转换为十进制数字

算法:

从右往左计算:

1. 若右边<=左边,则作加法

2. 若右边>左边,则作减法

 /**
	 * Calculate from right to left. following the rules below:
	 * 1. if right <= left, then result := right+left
	 * 2. or result := abs(result-left)
	 * 
	 * @author ouyangyewei
	 */
	public class Solution {
	    public int romanToInt(String s) {
	        final String ROMAN_STRING = "IVXLCDM";
	        final int[] ROMAN_VALUE = new int[]{1,5,10,50,100,500,1000};
	        
	        char lastRoman = 'I';
	        char currRoman = '\0';
	        int result = 0;
	        int length = s.length();
	        for (int i=length-1; i>=0; --i) {
	        	currRoman = s.charAt(i);
	        	int lastRomanValue = ROMAN_VALUE[ROMAN_STRING.lastIndexOf(lastRoman)];
	        	int currRomanValue = ROMAN_VALUE[ROMAN_STRING.lastIndexOf(currRoman)];
	        	if (lastRomanValue <= currRomanValue) {
	        		result += currRomanValue;
	        	}
	        	else {
	        		if (result > currRomanValue) {
	        			result = result - currRomanValue;
	        		}
	        		else {
	        			result = currRomanValue - result;
	        		}
	        	}
	        	
	        	lastRoman = currRoman;
	        }
	        
	        return result;
	    }
	}





[LeetCode]Roman to Integer,布布扣,bubuko.com

[LeetCode]Roman to Integer

标签:blog   java   2014   for   算法   io   

原文地址:http://blog.csdn.net/yeweiouyang/article/details/36625639

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!