【LeetCode】LeetCode——第12题:Integer to Roman

12. Integer to Roman

    My Submissions
Question Editorial Solution
Total Accepted: 62309  Total Submissions: 160814  Difficulty: Medium

Given an integer, convert it to a roman numeral.

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

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems













题目的大概意思是:给定一个整数,将它转换成对应的罗马数。

这道题难度等级:中等

一来可能对罗马数字不是很清楚,我们看到过的就是:I(表示1)、V(表示5)、X(表示10)。

1、其实总的是I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、M(1000);

2、相同的字母最多出现三次,且罗马数字没有0;

因此题目中给出了整数位1到3999的范围。

了解清楚后,就可以敲代码了,如下:

class Solution {
public:
    string intToRoman(int num) {
		string table[4][10] = {	{"", "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 res;
		int k = 0;
		while (num){
			res = table[k++][num % 10] + res;
			num /= 10;
		}
		return res;
    }
};
先是做了一个表,根据各个位的数字查表,然后组合罗马数字成字符串。

提交代码后AC掉,Runtime: 40 ms

你可能感兴趣的:(LeetCode,LeedCode)