LeetCode 12.整数转罗马数字
1.解法1
package LeetCode;
import java.util.HashMap;
import java.util.Map;
class Solution {
public static void main(String[] args) {
int num=58;
String result=intToRoman(num);
System.out.println(result);
}
public static String intToRoman(int num) {
Map<Integer, String> RomabMap = intiMap(); //IDEA提供了CTRL+ALT+V对该行快速根据变量类型自动生成变量.
//获取1784中的700,80,4
int ge=num%10; //4
int shi=(num-ge)%100; //80
int bai=(num-ge-shi)%1000; //700
int qian=num/1000*1000;
StringBuffer sb=new StringBuffer();
sb.append(RomabMap.get(qian));
sb.append(RomabMap.get(bai));
sb.append(RomabMap.get(shi));
sb.append(RomabMap.get(ge));
//null值替换
return sb.toString().replace("null","");
}
//定义罗马Map
//(整数,罗马数字)
//(1-9,罗马数字)
//(10-90,罗马数字)
// (100-900,罗马数字)
// (1000-3000,罗马数字)
public static Map<Integer,String>intiMap(){
Map<Integer,String> map=new HashMap<>();
//1-9
map.put(1,"I");
map.put(2,"II");
map.put(3,"III");
map.put(4,"IV");
map.put(5,"V");
map.put(6,"VI");
map.put(7,"VII");
map.put(8,"VIII");
map.put(9,"IX");
//10-90
map.put(10,"X");
map.put(20,"XX");
map.put(30,"XXX");
map.put(40,"XL");
map.put(50,"L");
map.put(60,"LX");
map.put(70,"LXX");
map.put(80,"LXXX");
map.put(90,"XC");
//100-900
map.put(100,"C");
map.put(200,"CC");
map.put(300,"CCC");
map.put(400,"CD");
map.put(500,"D");
map.put(600,"DC");
map.put(700,"DCC");
map.put(800,"DCCC");
map.put(900,"CM");
//1000-3000
map.put(1000,"M");
map.put(2000,"MM");
map.put(3000,"MMM");
return map;
}
}
2.枚举
package LeetCode;
class Solution {
public static void main(String[] args) {
int num=58;
String result=intToRoman(num);
System.out.println(result);
}
public static String intToRoman(int num) {
String []thousands={"","MM","MMM"};//""表示 千位为0的情况
String[]hundreds={"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
String[]tens={"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
String[]ones={"","I","II","III","IV","V","VI","VII","VIII","IX"};
return thousands[num/1000]+hundreds[num%1000/100]+tens[num%100/10]+ones[num%10];
}
}
3.贪心算法
package LeetCode;
class Solution {
public static void main(String[] args) {
int num=58;
String result=intToRoman(num);
System.out.println(result);
}
public static String intToRoman(int num) {
//把阿拉伯数字与罗马数字可能出现的所有情况和对应关系,放在两个数组中
//并且按照阿拉伯数字的大小降序排列,这是贪心选择思想,也是一种哈希思想
int []nums={1000,900,500,400,100,90,50,40,10,9,5,4,1};
String []romans={"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
StringBuilder newstring=new StringBuilder();
int index=0;
while (index<13){
//注意:这里是"=",表示尽量使用大的"面值"
while (num >= nums[index]) {
newstring.append(romans[index]);
num-=nums[index];
}
index++;
}
return newstring.toString();
}
}