利用上一題的程式:
Judge Small: Accepted!
Judge Large:Time Limit Exceeded
map<string,int> romanmp; void romanstr(string& roman, int num, char* symbol){if(num == 0)return;else if(num <= 3) roman.append(num, *symbol);else if(num == 4){roman.append(1,*symbol);roman.append(1,*(symbol+1));}else if(num <= 8){roman.append(1,*(symbol+1));roman.append(num-5,*symbol);}else if(num == 9){roman.append(1,*symbol);roman.append(1,*(symbol+2));}}string intToRoman(int num) { // Start typing your C/C++ solution below // DO NOT write int main() function char symbol[9] = {'I','V','X','L','C','D','M'}; string roman="";int scale = 1000;int p=6;while(num){int bit = num/scale;romanstr(roman, bit, symbol+p);num = num%scale;scale /= 10;p -= 2;}return roman; }int romanToInt(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function for(int i = 0;i <4000; i++)romanmp[intToRoman(i)] = i;return romanmp[s]; }
Accepted!
int romanToInt(string s) { // Start typing your C/C++ solution below // DO NOT write int main() function int length = s.length(); if(length <1) return 0;map<char,int> m;m['I'] = 1;m['V'] = 5;m['X'] = 10;m['L'] = 50;m['C'] = 100;m['D'] = 500;m['M'] = 1000;int i = length-1;int sum = m[s[i--]];while(i>=0)if(m[s[i+1]] > m[s[i]])sum -= m[s[i--]];elsesum += m[s[i--]];return sum; }