Roman to Integer

来源:互联网 发布:拓普康全站仪usp软件 编辑:程序博客网 时间:2024/05/17 00:04

Given a roman numeral, convert it to an integer.

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

思路:与Integer to Roman的规则一致,反推的过程。

Ref:http://www.cnblogs.com/springfor/p/3886477.html

class Solution {public:    int romanToInt(string s) {       if (s.empty()) {           return 0;       }              int result = 0;              for (int i = s.size() - 1; i >= 0; i--) {          if (s[i] == 'I') {              if (result >= 5) { //如果已经大于5,说明右边肯定出现过V, 所以左边出先的I一定是-1, 因为只有I,X,C可以写在左边                  result += -1;              }              else {                  result += 1;              }          }          else if (s[i] == 'V') { //如果为V, L, D, M直接相加即可              result += 5;          }          else if (s[i] == 'X') {              if (result >= 50) { //如果大于50,说明右边肯定出现过L,X出现在左边肯定是-10                  result += -10;              }              else {                  result += 10;              }          }          else if (s[i] == 'L') {              result += 50;          }          else if (s[i] == 'C') {              if (result >= 500) {                  result += -100;              }              else {                  result += 100;              }          }          else if (s[i] == 'D') {              result += 500;          }          else if (s[i] == 'M') {              result += 1000;          }       }              return result;    }};


0 0