标签:style blog color io ar for sp div on
Problem:
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 然后写一个子函数,输入数字和相应的位数级别,如个位为level 1,千为4.因为最多不会超过四千。所以可以如下。注意了,string用法很好,直接加就可以。
class Solution { private: string corRoman(int val, int level) { string base, media, large; string s = ""; if (level == 1) // 个位 { base = "I"; media = "V"; large = "X"; } else if (level == 2) { base = "X"; media = "L"; large = "C"; } else if (level == 3) { base = "C"; media = "D"; large = "M"; } else { base = "M"; } if (val == 0) return ""; if( val < 4) { for ( int i = 0; i < val; i++) s += base; return s; } if (val == 4) { return base + media; } if (val < 9) { s = media; for (int i = 5; i < val; i++) s+=base; return s; } return base + large; } public: string intToRoman(int num) { string s; int a; for (int i = 4; i > 0; i-- ) { a = num/pow(10,i - 1); num %= (int)pow(10, i - 1); s+=corRoman(a,i); } return s; } };
这样就Accept了。
leetcode第12题--Integer to Roman
标签:style blog color io ar for sp div on
原文地址:http://www.cnblogs.com/higerzhang/p/4025506.html