【LeetCode】Integer to Roman 和 Roman to Integer 解题报告

【题目】

Given a roman numeral, convert it to an integer. Or, Given an integer, convert it to a roman numeral.

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

【罗马数字】

1~9: {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};

10~90: {"X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};

100~900: {"C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};

1000~3000: {"M", "MM", "MMM"}.

【罗马数字转整数】

class Solution {public:int romanToInt(string s) {int ret = toNumber(s[0]);for (int i = 1; i < s.length(); i++) {if (toNumber(s[i – 1]) < toNumber(s[i])) {ret += toNumber(s[i]) – 2 * toNumber(s[i – 1]);} else {ret += toNumber(s[i]);}}return ret;}int toNumber(char ch) {switch (ch) {case 'I': return 1;case 'V': return 5;case 'X': return 10;case 'L': return 50;case 'C': return 100;case 'D': return 500;case 'M': return 1000;}return 0;}};

【整数转罗马数字】

public class Solution {public String intToRoman(int num) {String[][] roman = {{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},{"", "M", "MM", "MMM"}};String ret = "";int digit = 0;while (num != 0) {int remain = num % 10;ret = roman[digit][remain] + ret;digit++;num /= 10;}return ret;}}

参考 如下:

class Solution {public:string intToRoman(int num) {string str;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};for(int i=0;num!=0;++i){while(num>=value[i]){num-=value[i];str+=symbol[i];}}return str;}};

,谦受益,满招损。

【LeetCode】Integer to Roman 和 Roman to Integer 解题报告

相关文章:

你感兴趣的文章:

标签云: