来源:Leetcode
原帖:http://oj.leetcode.com/problems/integer-to-roman/
题目:
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. Solution: Buffer the roman numbers. Conversion range from high bit to low bit.
代码:
1]
2]
原帖:http://oj.leetcode.com/problems/integer-to-roman/
题目:
Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999. Solution: Buffer the roman numbers. Conversion range from high bit to low bit.
代码:
1]
class Solution {
public:
const string rom[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 intToRoman(int num) {
string res;
int i = 3;
while (num > 0) {
int divisor = (int)pow(10, i);
res += rom[i][num / divisor];
num %= divisor;
i--;
}
return res;
}
};
2]
class Solution {
public:
string intToRoman(int num) {
vector<int> value = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
unordered_map<int, string> map = {{1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"},
{100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"},
{9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}};
int i=0;
string res;
while (num) {
if (num >= value[i]) {
num -= value[i];
res += map[value[i]];
} else {
i++;
}
}
return res;
}
};
No comments:
Post a Comment