Given an integer, convert it to a roman numeral.给定一个整数,将其转换为罗马数字
Input is guaranteed to be within the range from 1 to 3999.
Subscribe to see which companies asked this question
用作数字的罗马字母共有七个,即Ⅰ(1),Ⅴ(5),Ⅹ(10),L(50),C(100),D(500),M(1000).
罗马字母记数有以下四条规则:
1.相同的数字连写,所表示的数等于这些数相加。如:XXX = 30,CC = 200。
2.如果大的数字在前,小的数字在后,所表示的数等于这些数相加。如:VIII = 8,LX = 60。
3.如果小的数字在前,大的数字在后,所表示的数等于从大数减去小数。如:IX = 9,XC = 90,CM = 900。
4.如果数字上面有一横线,表示这个数字增值1000倍。
罗马数字 数值
Ⅰ 1
Ⅱ 2
Ⅲ 3
Ⅳ 4
Ⅴ 5
Ⅵ 6
Ⅶ 7
Ⅷ 8
Ⅸ 9
X 10
XX 20
XXX 30
XL 40
L 50
LX 60
LXX 70
LXXX 80
XC 90
C 100
D 500
M 1000
package leetcode;
/**
* 1------I
* 5------V
* 10-----X
* 50-----L
* 100----C
* 500----D
* 1000---M
*
* @author Mouse
*
*/
public class Solution {
public static String intToRoman(int num) {
if (num<1&&num>3999) return null;
String result="";
while (num!=0) {
if (num>=1000) {
num-=1000;
result+="M";
continue;//跳过当前的循环执行下一个循环
}
if (num>=900) {
num-=900;
result+="CM";
continue;
}
if (num>=500) {
num-=500;
result+="D";
continue;
}
if (num>=400) {
num-=400;
result+="CD";
continue;
}
if (num>=100) {
num-=100;
result+="C";
continue;
}
if (num>=90) {
num-=90;
result+="XC";
continue;
}
if (num>=50) {
num-=50;
result+="L";
continue;
}
if (num>=40) {
num-=40;
result+="XL";
continue;
}
if (num>=10) {
num-=10;
result+="X";
continue;
}
if (num>=9) {
num-=9;
result+="IX";
continue;
}
if (num>=5) {
num-=5;
result+="V";
continue;
}
if (num>=4) {
num-=4;
result+="IV";
continue;
}
if (num>=1) {
num-=1;
result+="I";
continue;
}
}
return result;
}
public static void main(String[] args) {
String s=intToRoman(123);
System.out.println(s);
}
}