1. 程式人生 > >羅馬數字轉換為整數

羅馬數字轉換為整數

題目原型

Given a roman numeral, convert it to an integer.

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

首先要認識一些羅馬符號:I表示1,V表示5,X表示10,L表示50,C表示100,D表示500,M表示1000. 然後,從前往後掃描字串,設定4個變數:臨時變數(temp)、前一個數字變數(pre)、當前數字變數(current)、結果變數(result)。

1.如果當前處理的字元對應的值和上一個字元一樣,那麼臨時變數(temp)加上當前這個字元(current)

2.如果當前比前一個大,說明這一段的值應該是當前(current)

這個值減去前面記錄下的臨時變數(temp)中的值。例如 IV = 5 - 1。

3.如果當前比前一個小,那麼就可以先將臨時變數(temp)的值加到結果(result)中,臨時變數值(temp)變為當前變數(current)值,然後開始下一段記錄。比如VI = 5 + 1。

完成任何一步後,pre的值始終為current的值。

最後:result = result + temp

具體程式碼如下:

	public int getValue(char ch)
	{
		switch(ch)
		{
			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;
			default: return 0;
		}
	}
	public int romanToInt(String s)
	{
		int result = 0;
		int temp = 0;//設立臨時變數
		int current = 0;//當前變數
		int pre = 0;//前一個值
		char ch ;//儲存逐個讀取的單個字元
		temp = getValue(s.charAt(0));
		pre = temp;
		for(int i = 1;i<s.length();i++)
		{
			ch = s.charAt(i);
			current = getValue(ch);
			//分三種情況
			if(current==pre)
			{
				//當前值和前一個值相等
				temp+=current;
				pre = current;
			}
			else if(current<pre)
			{
				//當前值比前一個小
				result+=temp;
				temp = current;
				pre = current;
			}
			else
			{
				//當前值比前一個大
				temp = current - temp;
				pre = current;
			}
		}
		result+=temp;
		return result;
    }