leetCode:Integer to Roman
题目:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
解题:

public class Solution {
public String intToRoman(int num) {
String result = "";
int[] integer = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] roman = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
for(int i = 0;num!=0; i++){
while(num >= integer[i]){
result+=roman[i];
num-= integer[i];
}
}
return result;
}
}
想了半天的辣鸡代码:
import java.util.List;
import java.util.ArrayList;
public class Solution {
public String intToRoman(int num) {
List<Object> list = new ArrayList<Object>();
list = count(num);
return list.toString();
}
public List<Object> count(int num){
List<Object> list = new ArrayList<Object>();
int m = 1000,w = 500 ;
for(int i = 0; w>0||m>0;){
if(num/m > 0){
for(int j = 0; j < num/m; j++)
list.add(choose(m));
num = num % m;
m = m/10;
continue;
}
else if(num/w > 0){
for(int j = 0; j < num/w; j++)
list.add(choose(w));
num = num % w;
w = w/10;
}
}
return list;
}
public char choose(int n){
char result = 'A';
//I-1,V-5,X-10,L-50,C-100,D-500,M-1000
switch(n){
case 1000:
result = 'M';
break;
case 500:
result = 'D';
break;
case 100:
result = 'C';
break;
case 50:
result = 'L';
break;
case 10:
result = 'X';
break;
case 5:
result = 'V';
break;
case 1:
result = 'I';
break;
}
return result;
}
}

浙公网安备 33010602011771号