Problem
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Code
struct romanNode { char one; char five; char ten; romanNode* next; romanNode(char o,char f,char t):one(o),five(f),ten(t),next(0){} }; class Solution { public: int rtoi(const string& s,int i,int n,int sum,romanNode* node) { if(i == n && node == 0) return sum; if(i == n) return rtoi(s,i,n,sum*10,node->next); char one = node->one;char five = node->five;char ten = node->ten; if(s[i] != one && s[i] != five && s[i] != ten) return rtoi(s,i,n,sum*10,node->next); int j = i; while(j < n && (s[j] == one || s[j] == five || s[j] == ten)) ++j; int num = 0; int diff = j - i; if(diff == 1){ if(s[i] == one) num = 1; else num = 5; } else if(diff == 2){ if(s[i] == five) num = 6; else if(s[i + 1] == one) num = 2; else if(s[i + 1] == five) num = 4; else num = 9; } else if(diff == 3){ if(s[i] == one) num = 3; else num = 7; } else num = 8; return rtoi(s,j,n,sum*10 + num,node->next); } int romanToInt(string s) { // Note: The Solution object is instantiated only once and is reused by each test case. romanNode* node = new romanNode('M','O','O'); node->next = new romanNode('C','D','M'); node->next->next = new romanNode('X','L','C'); node->next->next->next = new romanNode('I','V','X'); int sum = 0; int ret = rtoi(s,0,s.size(),sum,node); delete node->next->next->next;delete node->next->next; delete node->next;delete node; return ret; }};
No comments:
Post a Comment