首页 > 代码库 > 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 }
LeetCode 13. Roman to Integer
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。