LeetCode-Integer to Roman

https://leetcode-cn.com/problems/integer-to-roman/

大概就是直接翻译题意,一遍通过。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Solution {
public String intToRoman(int num) {
char[] convertArr={'I','V','X','L','C','D','M'};
int currentPos=0;
StringBuilder sb=new StringBuilder();
while(num>0){
int t=num%10;
num/=10;
if(t<5){
if(t==4){
sb.append(convertArr[currentPos+1]);
sb.append(convertArr[currentPos]);
}else{
for(int i=0;i<t;i++) sb.append(convertArr[currentPos]);
}
}else{
if(t==9){
sb.append(convertArr[currentPos+2]);
sb.append(convertArr[currentPos]);
}else{
for(int i=0;i<t-5;i++) sb.append(convertArr[currentPos]);
sb.append(convertArr[currentPos+1]);
}
}
currentPos+=2;
}
return sb.reverse().toString();
}
}

看了答案以后发现了更方便的解法,直接穷举特殊 case,然后去减。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public String intToRoman(int num) {
String[] romans=new String[] {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int[] nums=new int[] {1000,900,500,400,100,90,50,40,10,9,5,4,1};
StringBuilder sb=new StringBuilder();
for(int i=0;i<nums.length;i++){
while(nums[i]<=num){
sb.append(romans[i]);
num-=nums[i];
}
}
return sb.toString();
}
}