首页 > 代码库 > Leetcode | Roman to Integer & Integer to Roman

Leetcode | Roman to Integer & Integer to Roman

Roman to Integer

Given a roman numeral, convert it to an integer.

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

搜了一下,才知道这道题可以写这么简洁。

 1 class Solution { 2 public: 3     int romanToInt(string s) { 4         if (s.empty()) return 0; 5         int dict[100]; 6         dict[I] = 1; dict[V] = 5; dict[X] = 10; dict[L] = 50; 7         dict[C] = 100; dict[D] = 500; dict[M] = 1000; 8      9         int ans = dict[s[0]];10         for (int i = 1; i < s.length(); ++i) {11             if (dict[s[i]] <= dict[s[i - 1]]) {12                 ans += dict[s[i]];13             } else {14                 ans = ans - 2 * dict[s[i - 1]] + dict[s[i]];15             }16         }17         return ans;18     }19 };

Integer to Roman

Given an integer, convert it to a roman numeral.

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

 1 class Solution { 2 public: 3     string intToRoman(int num) { 4         string str[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"}; 5         int value[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; 6          7         string ret = ""; 8         for (int i = 0; i < 13; ++i) { 9             while (num >= value[i]) {10                 ret += str[i];11                 num -= value[i];12             }13         }14         return ret;15     }16 };

 

Leetcode | Roman to Integer & Integer to Roman