/****************************LeetCode 13 Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.**********************/ int romanToInt(string s) { if (s.size()<1) { return 0; } //使用hashmap更合适 int weight[26]; memset(weight, 0, sizeof(weight)); weight['I' - 'A'] = 1; weight['V' - 'A'] = 5; weight['X' - 'A'] = 10; weight['L' - 'A'] = 50; weight['C' - 'A'] = 100; weight['D' - 'A'] = 500; weight['M' - 'A'] = 1000; int size = s.size(); int pivot = weight[s.at(size - 1) - 'A']; int result = pivot; for (int ii = size - 2; ii >= 0; ii--) { int cur = weight[s[ii] - 'A']; if (cur >= pivot) // 加上该位上值 { result += cur; pivot = cur; } else //减去该位上的值 { result -= cur; pivot = cur; } } return result;}
新闻热点
疑难解答