首页 > 代码库 > LeetCode 13. Roman to Integer

LeetCode 13. Roman to Integer

https://leetcode.com/problems/roman-to-integer/#/description

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

  • 字符串简单题,要搞清楚转换规则。如果当前字母比前一个大,则相减,比如IV = 5 - 1;否则就相加,比如VI = 5 + 1,II = 1 + 1。
  • 罗马数字_百度百科
    • http://baike.baidu.com/link?url=JBuRWsGjAmYIlIhaPN_ywmIJBMrTWT6iKb2-WhqyTA6RqitOQuqnvQ2PHVfelAf00iGWWtgTzUjB3W4YMR0XWLfadA6YVi_s2J1aUgb-n1eBewvqGmyRpdH3VsVVs4q3

 

技术分享
 1 #include <iostream> 2 #include <string> 3 using namespace std; 4  5 class Solution { 6 public: 7     inline int map(const char inCh) 8     { 9         switch (inCh)10         {11             case I: return 1;12             case V: return 5;13             case X: return 10;14             case L: return 50;15             case C: return 100;16             case D: return 500;17             case M: return 1000;18             default:    return 0;19         }20         21     }22     23     int romanToInt(string s)24     {25         int result = 0;26         27         for (size_t i = 0; i < s.size(); i ++) {28             if ((i > 0) && (map(s[i]) > map(s[i - 1]))) {29                 result += map(s[i]) - 2 * map(s[i - 1]);30             } else {31                 result += map(s[i]);32             }33         }34         35         return result;36     }37 };38 39 int main ()40 {41     Solution testSolution;42     string sTest[] = {"XXI", "XXIX"};43 44     for (int i = 0; i < 2; i ++)45         cout << testSolution.romanToInt(sTest[i]) << endl;46     47     return 0;48 }
View Code

 

LeetCode 13. Roman to Integer