您的位置:首页 > 其它

LintCode_418_整数转罗马数字

2016-04-14 01:04 513 查看
public class Solution {
/**
* @param n The integer
* @return Roman representation
*/
public String intToRoman(int n) {
// Write your code here
// 基本字符	   相应的阿拉伯数字表示为
// I           1
// V           5
// X           10
// L           50
// C           100
// D           500
// M           1000

int[] numbers = { 1000,  900,  500,  400,  100,   90,  50,   40,   10,    9,    5,    4, 1 };
String[] letters = { "M",  "CM",  "D",  "CD", "C",  "XC", "L",  "XL",  "X",  "IX", "V",  "IV", "I" };
String result ="" ;
for(int i = 0;i<13;i++){
if(n >= numbers[i]){
int count = n/numbers[i];
n = n%numbers[i];
for(int j=0;j<count ;j++){
result += letters[i];
}
}
}
return result;
}
}


给定一个整数,将其转换成罗马数字。
返回的结果要求在1-3999的范围内。

您在真实的面试中是否遇到过这个题?

Yes

说明

什么是 罗马数字?

https://en.wikipedia.org/wiki/Roman_numerals
https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
http://baike.baidu.com/view/42061.htm

样例

4
->
IV

12
->
XII

21
->
XXI

99
->
XCIX

更多案例,请戳 http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
自己写的啰里啰唆 在网上找到这个算法 应该是比较优化的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: