Roman to Integer Solutions in C++
Number 13
Difficulty Easy
Acceptance 55.8%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/roman-to-integer/// Author : Hao Chen// Date : 2014-07-17#include <iostream>#include <string>using namespace std;int romanCharToInt(char ch){int d = 0;switch(ch){case 'I':d = 1;break;case 'V':d = 5;break;case 'X':d = 10;break;case 'L':d = 50;break;case 'C':d = 100;break;case 'D':d = 500;break;case 'M':d = 1000;break;}return d;}int romanToInt(string s) {if (s.size()<=0) return 0;int result = romanCharToInt(s[0]);for (int i=1; i<s.size(); i++){int prev = romanCharToInt(s[i-1]);int curr = romanCharToInt(s[i]);//if left<right such as : IV(4), XL(40), IX(9) ...if (prev < curr) {result = result - prev + (curr-prev);}else{result += curr;}}return result;}int main(int argc, char**argv){string s("XL");if (argc>1){s = argv[1];}cout << s << " : " << romanToInt(s) << endl;return 0;}
C++ solution by pezy/LeetCode
#include <string>using std::string;class Solution {public:int romanToInt(string s) {int res = 0;for (auto iter = s.rbegin(); iter != s.rend(); ++iter)switch (*iter){case 'I': res += res >= 5 ? -1 : 1; break;case 'V': res += 5; break;case 'X': res += 10 * (res >= 50 ? -1 : 1); break;case 'L': res += 50; break;case 'C': res += 100 * (res >= 500 ? -1 : 1); break;case 'D': res += 500; break;case 'M': res += 1000; break;}return res;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/roman-to-integer/description//// Author : liuyubobobo/// Time : 2018-09-17#include <iostream>#include <unordered_map>using namespace std;/// Ad-Hoc/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:int romanToInt(string s) {unordered_map<char, int> map = {{'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, {'C', 100}, {'D', 500}, {'M', 1000}};int res = 0;for(int i = 0; i < s.size(); i ++)if(i + 1 < s.size() && map[s[i]] < map[s[i + 1]]){res += map[s[i + 1]] - map[s[i]];i ++;}elseres += map[s[i]];return res;}};int main() {return 0;}