标签:
Roman to Integer
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
从左到右遍历每个字符,并记录上个字符来处理双字符情况即可。
class Solution { public: int romanToInt(string s) { int n = 0; char lastC = 0; for(int i = 0; i < s.size(); i ++) { switch(s[i]) { case ‘I‘: n += 1; lastC = s[i]; break; case ‘V‘: if(lastC == ‘I‘) {//IV n -= 1; n += 4; lastC = 0; } else { n += 5; lastC = s[i]; } break; case ‘X‘: if(lastC == ‘I‘) {//IX n -= 1; n += 9; lastC = 0; } else { n += 10; lastC = s[i]; } break; case ‘L‘: if(lastC == ‘X‘) {//XL n -= 10; n += 40; lastC = 0; } else { n += 50; lastC = s[i]; } break; case ‘C‘: if(lastC == ‘X‘) {//XC n -= 10; n += 90; lastC = 0; } else { n += 100; lastC = s[i]; } break; case ‘D‘: if(lastC == ‘C‘) {//CD n -= 100; n += 400; lastC = 0; } else { n += 500; lastC = s[i]; } break; case ‘M‘: if(lastC == ‘C‘) {//CM n -= 100; n += 900; lastC = 0; } else { n += 1000; lastC = s[i]; } break; default: return 0; } } return n; } };
标签:
原文地址:http://www.cnblogs.com/ganganloveu/p/4176367.html