罗马数字转换为十进制数

//例子:罗马数字和十进制对照表(部分)

I - 1

//II - 2

//III - 3

//IV - 4

//V – 5

//VI - 6

//VII – 7

//VIII - 8

//IX - 9

//X – 10

//XI – 11

//XII – 12

//XIII – 13

//XIV – 14

//XV – 15

//XVI – 16

//XVII – 17

//XVIII – 18

//XIX – 19

//XX – 20

//XXI – 21

//XXII – 22

//XXVIII - 28

//XXIX - 29

//XXX - 30

//XL - 40

//L - 50

//LX - 60

//LXX - 70

//LXXX - 80

//XC - 90

//XCIX - 99

//C - 100 centum

//CI - 101 centum et unus

//CXCIX - 199

//CC - 200

//CCC - 300

//CD - 400

//D - 500

//DCLXVI - 666

//M - 1,000

//MCMXCIX - 1,999

//MM - 2,000

//MMM - 3,000

//MMMM - 4,000

//MMMMCMXCIX - 4,999

 

#include 
#include 
using namespace std;

map m_hash;

void init()
{
	m_hash['I'] = 1;
	m_hash['V'] = 5;
	m_hash['X'] = 10;
	m_hash['L'] = 50;
	m_hash['C'] = 100;
	m_hash['D'] = 500;
	m_hash['M'] = 1000;

}

int getSum(char str[])
{
	int sum = 0;
	int n = strlen(str);
	int i = 0;

	sum += m_hash[str[0]];
	for (i = 1;i < n; ++i)
	{
		sum +=  m_hash[str[i]];
		if (m_hash[str[i]] > m_hash[str[i - 1]])
		{
			sum -= 2 * m_hash[str[i-1]];
		}

	}

	return sum;
}

int main()
{
	init();
	char str[10];//罗马数字
	while(scanf("%s", str) != EOF)
	{
		//sum 表示 十进制数字
		int sum = getSum(str);
		printf("%d\n", sum);
	}

	return 0;
}


 

你可能感兴趣的:(c/c++,面试题目)