Roman to Integer (link)Jan 15 '12
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
class Solution { int romanToDigit(char c){ int r = 0; switch(c){ case 'I': r = 1; break; case 'V': r = 5; break; case 'X': r = 10; break; case 'L': r = 50; break; case 'C': r = 100; break; case 'D': r = 500; break; case 'M': r = 1000; break; } return r; } public: int romanToInt(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function if (s.empty()) return 0; int num = romanToDigit(s[s.length()-1]); int prev = num; for(int ii = s.length() - 2; ii >= 0; --ii){ int const digitNum = romanToDigit(s[ii]); if (digitNum < prev) num -= digitNum; else num += digitNum; prev = digitNum; } return num; } };
No comments:
Post a Comment