题目: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.
题目翻译:
给定一个整数,将其转换成罗马数字。
输入在1到3999的范围内。
从num的高位到低位依次转换。
C++实现:
class Solution {
public:
string intToRoman(int num) {
const int base[] = {1000, 900, 500, 400, 100, 90, 50,
40, 10, 9, 5, 4, 1};
const string roman[] = {"M", "CM", "D", "CD", "C", "XC", "L",
"XL", "X", "IX", "V", "IV", "I"};
string result;
for(int i = 0; num > 0; ++i)
{
int count = num / base[i];
num %= base[i];
while(count > 0)
{
result += roman[i];
--count;
}
}
return result;
}
};
Java实现:
public class Solution {
public String intToRoman(int num) {
int[] base = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 };
String[] roman = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X",
"IX", "V", "IV", "I" };
String result = "";
for (int i = 0; num > 0; ++i) {
int count = num / base[i];
num %= base[i];
while (count > 0) {
result += roman[i];
--count;
}
}
return result;
}
}
Python实现:
class Solution:
# @return a string
def intToRoman(self, num):
base = [1000, 900, 500, 400, 100, 90, 50,
40, 10, 9, 5, 4, 1]
roman = ["M", "CM", "D", "CD", "C", "XC", "L",
"XL", "X", "IX", "V", "IV", "I"]
result = ""
i = 0
while num > 0:
count = num / base[i]
num %= base[i]
while count > 0:
result += roman[i]
count -= 1
i += 1
return result
感谢阅读,欢迎评论!