您的位置:首页 > 编程语言 > Java开发

[Leetcode] Integer to Roman (Java)

2013-12-26 19:08 375 查看
Given an integer, convert it to a roman numeral.

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

阿拉伯数字转换成罗马数字,细心

public class IntegertoRoman {
public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
while(num>=1000) {
sb.append('M');
num-=1000;
}
if(num>=900){
sb.append("CM");
num-=900;
}else if(num>=500){
sb.append("D");
num-=500;
while(num>=100) {
sb.append("C");
num-=100;
}
}else if(num>=400) {
sb.append("CD");
num-=400;
}else {
while(num>=100) {
sb.append("C");
num-=100;
}
}
if(num>=90) {
sb.append("XC");
num-=90;
}else if(num>=50) {
sb.append('L');
num-=50;
while(num>=10) {
sb.append("X");
num-=10;
}
}else if(num>=40) {
sb.append("XL");
num-=40;
}else {
while(num>=10) {
sb.append("X");
num-=10;
}
}
if(num==9)
sb.append("IX");
else if(num>4) {
sb.append('V');
num-=5;
while(num>0) {
sb.append("I");
num-=1;
}
}else if(num==4)
sb.append("IV");
else {
while(num>0) {
sb.append("I");
num-=1;
}
}
return sb.toString();
}
public static void main(String[] args) {
int num = 40;
System.out.println(new IntegertoRoman().intToRoman(num));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: