标签:
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 values[] = {1000, 500, 100, 50, 10, 5, 1 }; char numerals[] = {‘M‘, ‘D‘, ‘C‘, ‘L‘, ‘X‘, ‘V‘, ‘I‘ }; int i = 0, j = 0, result = 0; while(i < s.length()){ if(s[i] != numerals[j]){ j++; continue; } if(i+1<s.length() && j-1>=0 && s[i+1] == numerals[j-1]){ result += values[j-1]-values[j]; i+=2; } else if(i+1<s.length() && j-2>=0 && s[i+1] == numerals[j-2]){ result += values[j-2]-values[j]; i+=2; } else{ result += values[j]; i++; } } return result; } };
标签:
原文地址:http://www.cnblogs.com/qionglouyuyu/p/4671714.html