leetcode C++ 13. 羅馬數字轉整數 羅馬數字包含以下七種字符: I, V, X, L,C,D 和 M。

一、C++代碼:


int romanToInt(string s) {
	int res = 0;
	map<char, int> mapRoman = { {'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000} };
	while (s.size() > 0) {
		char temp = s.back();
		int num1 = mapRoman.find(temp)->second;
		s.pop_back();
		if (s.size() > 0) {
			char temp1 = s.back();
			int num2 = mapRoman.find(temp1)->second;
			if (num1 / num2 == 5 || num1 / num2 == 10 && num1%num2 == 0) {
				res += num1 - num2;
				s.pop_back();
			}
			else {
				res += num1;
			}
		}
		else {
			res += num1;
		}
	}
	return res;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章