Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

罗马数字转int

  • Loading branch information...
commit 470135be51f7afc42d8396286d8017decff21980 1 parent 9c53d0d
= authored
Showing with 52 additions and 0 deletions.
  1. +52 −0 roman-to-integer.cpp
View
52 roman-to-integer.cpp
@@ -0,0 +1,52 @@
+
+
+// http://oj.leetcode.com/problems/roman-to-integer/
+
+// Roman to Integer
+
+// Given a roman numeral, convert it to an integer.
+
+// Input is guaranteed to be within the range from 1 to 3999.
+
+// 罗马数字的规则 http://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
+
+#include <map>
+
+using namespace std;
+
+class Solution {
+public:
+ int romanToInt(string s) {
+ map<char, int> romanMap = initRomanNumMap();
+ int num = romanMap[s[0]];
+ int len = s.length();
+ if(len==1) {
+ return romanMap[s[0]];
+ }
+
+ for(string::iterator it = s.begin(); it!=s.end(); it++) {
+ char first = *it;
+ char next = *(it+1);
+ if(romanMap[first]>=romanMap[next]) {
+ num = num + romanMap[next];
+ }else{
+ num = num - romanMap[first] + (romanMap[next] - romanMap[first]);
+ }
+ }
+ return num;
+
+ }
+
+ map<char, int> initRomanNumMap() {
+ map<char, int> romanMap;
+ romanMap['I'] = 1;
+ romanMap['V'] = 5;
+ romanMap['X'] = 10;
+ romanMap['L'] = 50;
+ romanMap['C'] = 100;
+ romanMap['D'] = 500;
+ romanMap['M'] = 1000;
+
+ return romanMap;
+ }
+};
Please sign in to comment.
Something went wrong with that request. Please try again.