leetcode-12. Integer to Roman
题目:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
主要思路就是根据10*,90*,50*,40*,这几个点分段处理就行。没有特别需要注意的。
public class Solution {
public String intToRoman(int num) {
StringBuilder sb = new StringBuilder();
if(num>999){
int M = num/1000;
num -= M*1000;
while(M-- !=0){
sb.append("M");
}
}
if(num > 899){
num -=900;
sb.append("CM");
}
if(num > 499){
num -= 500;
int C = num/100;
num -= C * 100;
sb.append("D");
while(C-- != 0)
sb.append("C");
}
if(num >399){
num -= 400;
sb.append("CD");
}
if(num > 99){
int C = num/100;
num -= C * 100;
while(C-- != 0)
sb.append("C");
}
if(num > 89){
num -= 90;
sb.append("XC");
}
if(num > 49){
num -= 50;
sb.append("L");
int X = num/10;
num -= X * 10;
while(X-- != 0){
sb.append("X");
}
}
if(num > 39){
num -= 40;
sb.append("XL");
}
if(num > 9){
int X = num/10;
num -= X * 10;
while(X-- != 0)
sb.append("X");
}
if(num > 8){
num -= 9;
sb.append("IX");
}
if(num > 4){
num -= 5;
sb.append("V");
while(num-- != 0)
sb.append("I");
}
if(num > 3){
num -= 4;
sb.append("IV");
}
if(num > 0){
while(num-- != 0)
sb.append("I");
}
return sb.toString();
}
}