题目
题目链接:https://leetcode-cn.com/problems/integer-to-roman/
题目解析:我的方法就是暴力,将千,百,十,个位一个一个切分开,然后再根据特性一个个写成字符串然后再拼接在一起。
还有一种方法,就是将数值和字符分别放在两个数组中,用数去减每一个数组中的数值,然后相对应的就加上每一个数组对应的字符串
方法的链接:https://leetcode-cn.com/problems/integer-to-roman/solution/javazheng-shu-zhuan-luo-ma-shu-zi-by-xuebuhui0729/
代码
我的方法:太麻烦了,但是条例清晰
class Solution {
public String intToRoman(int num) {
StringBuffer sb = new StringBuffer();
String one = "";//个位
String two = "";//十位
String three = "";//百位
String four = "";//千位
//如果数目大于一千
if(num>=1000) {
int four1 = num/1000;
num=num%1000;
int three1 = num/100;
num=num%100;
int two1 = num/10;
int one1 = num%10;
four = four(four1);
three = three(three1);
one = one(one1);
two = two(two1);
sb.append(four);
sb.append(three);
sb.append(two);
sb.append(one);
}else if(num>=100) {//如果数目大于100
int three1 = num/100;
int two1 = (num%100)/10;
int one1 = num%10;
three = three(three1);
one = one(one1);
two = two(two1);
sb.append(three);
sb.append(two);
sb.append(one);
}else if(num>=10) {//数目大于10
int two1 = num/10;
int one1 = num%10;
one = one(one1);
two = two(two1);
sb.append(two);
sb.append(one);
}else {//数目为个位数
one = one(num);
sb.append(one);
}
return sb.toString();
}
//千位字符串书写
private static String four(int four1) {
StringBuffer sb = new StringBuffer();
for(int i=0;i<four1;i++) {
sb.append("M");
}
return sb.toString();
}
//百位字符串书写
private static String three(int three1) {
StringBuffer sb = new StringBuffer();
if(three1==9) {
sb.append("CM");
}else if(three1>=5&&three1<9) {
sb.append("D");
for(int i=0;i<three1-5;i++)
sb.append("C");
}else if(three1==4) {
sb.append("CD");
}else {
for(int i=0;i<three1;i++)
sb.append("C");
}
return sb.toString();
}
//十位字符串书写
private static String two(int two1) {
StringBuffer sb = new StringBuffer();
if(two1==9) {
sb.append("XC");
}else if(two1>=5&&two1<9) {
sb.append("L");
for(int i=0;i<two1-5;i++)
sb.append("X");
}else if(two1==4) {
sb.append("XL");
}else {
for(int i=0;i<two1;i++)
sb.append("X");
}
return sb.toString();
}
//个位字符串书写
private static String one(int num) {
StringBuffer sb = new StringBuffer();
if(num>=5&&num<9) {
sb.append("V");
for(int i = 0;i<num-5;i++) {
sb.append("I");
}
}else if(num==9) {
sb.append("IX");
}else if(num==4) {
sb.append("IV");
}else if(num<4){
for(int i=0;i<num;i++)
sb.append("I");
}
return sb.toString();
}
}
第二种更快速更简便的方法:
class Solution {
int[] number = {1000,900,500,400,100,90,50,40,10,9,5,4,1} ;
String[] s = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"} ;
StringBuilder sb = new StringBuilder() ;
public String intToRoman(int num) {
for(int i = 0 ; i < number.length ; i++){
while(num >= number[i]){
sb.append(s[i]) ;
num -= number[i] ;
}
if(num == 0){
break ;
}
}
return sb.toString() ;
}
}
作者:xuebuhui0729
链接:https://leetcode-cn.com/problems/integer-to-roman/solution/javazheng-shu-zhuan-luo-ma-shu-zi-by-xuebuhui0729/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。