标签:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
这是一种首先会想到的思路:一个一个字母解析,先解析是不是双字母罗马数字,如果不是就按单字母罗马数字解析。
/********************************* * 日期:2015-01-22 * 作者:SJF0115 * 题目: 13.Roman to Integer * 网址:https://oj.leetcode.com/problems/roman-to-integer/ * 结果:AC * 来源:LeetCode * 博客: **********************************/ #include <iostream> using namespace std; class Solution { public: int romanToInt(string s) { int result = 0; int len = s.length(); if(len <= 0){ return result; }//if for(int i = 0;i < len;++i){ if(s[i] == 'M'){ result += 1000; }//if else if(s[i] == 'D'){ result += 500; } else if(s[i] == 'C'){ if(s[i+1] == 'M'){ result += 900; ++i; }//if else if(s[i+1] == 'D'){ result += 400; ++i; } else{ result += 100; } } else if(s[i] == 'L'){ result += 50; } else if(s[i] == 'X'){ if(s[i+1] == 'C'){ result += 90; ++i; }//if else if(s[i+1] == 'L'){ result += 40; ++i; } else{ result += 10; } } else if(s[i] == 'V'){ result += 5; } else if(s[i] == 'I'){ if(s[i+1] == 'X'){ result += 9; ++i; } else if(s[i+1] == 'V'){ result += 4; ++i; } else{ result += 1; } } }//for return result; } }; int main(){ Solution solution; string roman = "XCVIII"; int result = solution.romanToInt(roman); // 输出 cout<<result<<endl; return 0; }
标签:
原文地址:http://blog.csdn.net/sunnyyoona/article/details/43020099