关闭

leetcode 012 —— Integer to Roman

151人阅读 评论(0) 收藏 举报
分类:

Given an integer, convert it to a roman numeral.

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

知识补充:

I、V、	  X、L、	C、D	和M,分别表示	1、5、	10、50、	100、500	和1000;

思路:依次求千,百,十,个,转换成字符串        下面的方法是枚举,空间复杂度有待完善,更简洁的代码以后附上

class Solution {
public:
string intToRoman(int num) {
	int qian =num/1000;
	int bai = (num - qian * 1000) / 100;
	int shi = (num - qian * 1000 - 100 * bai) / 10;
	int ge = num % 10;

	string s1 (qian, 'M');
	string s2 = fun(bai, 3);
	string s3 = fun(shi, 2);
	string s4 = fun(ge, 1);
	
	string s = s1 + s2 + s3 + s4;
	return s;

}

string fun(int n,int myCase){
	if (n == 0)
		return "";
	vector<string> vec;
	switch(myCase){
	case 1: 	vec = { "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
				break;
	case 2: 	vec = { "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
				break;
	case 3: 	vec = { "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
				break;
	}

	return vec[n - 1];
}

};



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:25934次
    • 积分:2054
    • 等级:
    • 排名:第18652名
    • 原创:188篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    最新评论