Roman to Integer

Given a roman numeral, convert it to an integer.

首先介绍罗马数字

罗马数字共有七个,即I(1),V(5),X(10),L(50),C(100),D(500),M(1000)。按照下面的规则可以表示任意正整数。

重复数次:一个罗马数字重复几次,就表示这个数的几倍。

右加左减:在一个较大的罗马数字的右边记上一个较小的罗马数字,表示大数字加小数字。
在一个较大的数字的左边记上一个较小的罗马数字,表示大数字减小数字。但是,左减不能跨越等级。比如,99不可以用IC表示,用XCIX表示。

  • 重写: III(3) XX(20) CC(200)

  • 左减: IX(9) XL(40) CD(400)

  • 右加: VII(7) XI(11) LX(60)

  • 综合前三种方法:XLV(L-X+V,45) LXII(L+X+I+I,62)

若在数字上方加一横线,表示增大1000倍。
XIX (19000)

import java.util.HashMap;

public class Solution {
public static int romanToInt(String s) {
	if (s == null || s.length() == 0)
		return 0;
	int len = s.length();
	HashMap<Character, Integer> map = new HashMap<Character, Integer>();
	map.put('I', 1);
	map.put('V', 5);
	map.put('X', 10);
	map.put('L', 50);
	map.put('C', 100);
	map.put('D', 500);
	map.put('M', 1000);
	int result = map.get(s.charAt(len - 1));
	int pivot = result;
	for (int i = len - 2; i >= 0; i--) {
		int curr = map.get(s.charAt(i));
		if (curr >= pivot) {
			result += curr;
		} else {
			result -= curr;
		}
		pivot = curr;
	}
	return result;
   }
 }

从后到后,curr为当前所指的字母,pivot跟随着curr,用于比较,当后面一个数字小于等于curr时,则右加。否则左减。

相关文章:

  • 2021-07-08
  • 2022-02-11
  • 2022-01-14
  • 2021-12-24
  • 2022-01-18
  • 2022-02-11
  • 2021-12-17
  • 2022-01-16
猜你喜欢
  • 2022-12-23
  • 2021-12-14
  • 2018-11-26
  • 2022-12-23
  • 2021-09-08
  • 2022-01-17
  • 2021-09-20
相关资源
相似解决方案