To tell you the truth, these two words marked as medium and simple on the leetcode have made my egg ache for half a day. Probably because of the congenital to the Arabic numeral unfamiliar relationship, so in do two questions incredibly not a little feeling!!!!!
Converting Roman numerals to Arabic numerals is simple: scanning the entire string from left to right can be done only when the previous number is smaller than the latter and requires special processing (subtraction required).
Class solution {public:int romantoint (string s) {if (S.empty ()) {return 0;} int letter[256];for (int i=0; i<256; i++) {letter[i] = 0;} letter[' I '] = 1;letter[' V '] = 5;letter[' X '] = 10;letter[' L '] = 50; letter[' C '] = 100;letter[' D '] = 500;letter[' M '] = 1000;int result = 0;unsigned int cur = 0;unsigned int next = 1;while (Next < s.size ()) {if (Letter[s[cur]] < letter[s[next]) {Result = result + (Letter[s[next]] - letter[s[cur]]);cur = cur + 2;next = Next + 2;} else{result = result + letter[s[cur]];cur = cur + 1;next = next + 1;}} if (Cur < s.size ()) {result = result + letter[s[cur]];} return result;}};
Convert Arabic numerals to Roman numerals some of the eggs hurt .... But saw the Leetcode on the highest vote of a method, the original also only need to be thousands, hundred, 10 and so on to express out both.
Class solution {public: string inttoroman (Int num) { string result = ""; if (num < 1 | | num > 3999) { return result; } string m[] = {"", "M", "MM", " MMM "}; //thousand, from 1000 to 3000 string c[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; //hundred, from 100 to 900 string x[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX ", " LXXX ", " XC "}; //10-bit, from 10 to 90 string i[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", " VIII ", " IX "}; //bits, from 1 to 9 result = m[ num / 1000] + c[(num % 1000) / 100] + x[(num % 100 ) / 10] + I[num % 10]; }};
leetcode--conversion of Roman numerals and Arabic numerals