說實話,這兩道在leetcode上標記爲中等和簡單的題卻讓我蛋疼了半天。多是由於先天對阿拉伯數字不熟悉的關係,因此在作兩道題的竟然沒有一點感受!!!!!code
將羅馬數字轉化爲阿拉伯數字比較簡單:從左向右掃描整個字符串既可,只有在前一個數字比後一個數字小的時候須要作特殊處理(須要作減法)。leetcode
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; } };
將阿拉伯數字轉化爲羅馬數字就有些蛋疼了。。。。可是看了leetcode上投票最高的一個方法後恍然大悟,原來也只須要將千位,百位,十位等等表示出來既可。字符串
class Solution { public: string intToRoman(int num) { string result = ""; if (num < 1 || num > 3999) { return result; } string M[] = {"", "M", "MM", "MMM"}; //千位,從1000到3000 string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; //百位,從100到900 string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; //十位,從10到90 string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; //個位,從1到9 result = M[num / 1000] + C[(num % 1000) / 100] + X[(num % 100) / 10] + I[num % 10]; } };