Integer to Roman Solutions in C++
Number 12
Difficulty Medium
Acceptance 55.1%
Link LeetCode
Other languages —
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/integer-to-roman/// Author : Hao Chen// Date : 2014-07-17#include <stdlib.h>#include <string>#include <iostream>using namespace std;//greeding algorithmstring intToRoman(int num) {string symbol[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};int value[] = {1000,900,500,400, 100, 90, 50, 40, 10, 9, 5, 4, 1};string result;for(int i=0; num!=0; i++){while(num >= value[i]){num -= value[i];result+=symbol[i];}}return result;}int main(int argc, char** argv){int num = 1234;if (argc>0){num = atoi(argv[1]);}cout << num << " : " << intToRoman(num) << endl;return 0;}
C++ solution by pezy/LeetCode
#include <string>#include <unordered_map>using std::string;class Solution {public:string intToRoman(int num) {std::map<int, string> map = {{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"},{90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}};string ret;for (auto iter = map.rbegin(); iter != map.rend(); ++iter)while (num >= iter->first){ret += map[iter->first];num -= iter->first;}return ret;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/integer-to-roman/description//// Author : liuyubobobo/// Time : 2018-09-16#include <iostream>#include <cmath>using namespace std;/// Ad-Hoc/// Time Complexity: O(1)/// Space Complexity: O(1)class Solution {public:string intToRoman(int num) {string res = "";string one[] = {"I", "X", "C", "M", ""}, five[] = {"V", "L", "D", ""};for(int k = 3; k >= 0; k --){int b = (int)pow(10, k);if(num >= b){int x = num / b;res += rome(x, one[k], five[k], one[k + 1]);num %= b;}}return res;}private:string rome(int x, string one, string five, string ten){if(x <= 3)return string(x, one[0]);else if(x == 4)return one + five;else if(x <= 8)return five + string(x - 5, one[0]);// x == 9return one + ten;}};int main() {return 0;}