Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
A:
--------------2 nd pass-------------------------
思路:
就是把 单位放到数组里,一个个 单位 来对比。
public class Solution {
public String intToRoman(int num) {
HashMap<Integer,Character> map = new HashMap();
StringBuffer buf = new StringBuffer();
map.put(1,'I');
map.put(5,'V');
map.put(10,'X');
map.put(50,'L');
map.put(100,'C');
map.put(500,'D');
map.put(1000,'M');
int [] A = {1000,500,100,50,10,5,1};
int i =0;
while(num>0 && i<A.length){
if(num/A[i] == 0){
i++;
}else if((i == 1 || i == 3 | i == 5 ) && num/A[i+ 1]== 9 ){
buf.append(""+map.get(A[i+1])+map.get(A[i-1]));
num -= 9*A[i+1];
}else if(num/A[i]==4 ){
buf.append(""+map.get(A[i])+map.get(A[i-1]));
num -= 4*A[i];
}else{
buf.append(""+map.get(A[i]));
num -= A[i];
}
}
return buf.toString();
}
}
Mistakes:1: 45 不能写成 VL的形式。 只有10的单位的,可以写成减法的形式。
只有 I X C 才能被放到前面 做减法。
-----------1st pass--------------------
public class Solution {
public String intToRoman(int num) {
// Symbol I V X L C D M
// Value 1 5 10 50 100 500 1,000
Map<Integer,String> map = new HashMap<>();
map.put(1000,"M");
map.put(900,"CM");
map.put(500,"D");
map.put(400,"CD");
map.put(100,"C");
map.put(90,"XC");
map.put(50,"L");
map.put(40,"XL");
map.put(10,"X");
map.put(9,"IX");
map.put(5,"V");
map.put(4,"IV");
map.put(1,"I");
int[]A = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
String res = "";
int i =0;
while(num > 0){
if(num >= A[i]){
num-= A[i];
res += map.get(A[i]);
}else{
i++;
}
}
return res;
}
}
Mistakes:
1: 开始的时候, buffer.replace(start ,end, String)的时候, 要 replace掉4个长度的string, 那么 end = start+4即可。 而不是 end = start+5;
Learned:
1: 罗马数字的基本单位:
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000
Numbers are formed by combining symbols together and adding the values. So II is two ones, i.e. 2, and XIII is a ten and three ones, i.e. 13. There is no zero in this system, so 207, for example, is CCVII, using the symbols for two hundreds, a five and two ones. 1066 is MLXVI, one thousand, fifty and ten, a five and a one.
Symbols are placed from left to right in order of value, starting with the largest. However, in a few specific cases,[2] to avoid four characters being repeated in succession (such as IIII or XXXX) these can be reduced using subtractive notation as follows:[3][4]
the numeral I can be placed before V and X to make 4 units (IV) and 9 units (IX) respectively
X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern[5]
n example using the above rules would be 1904: this is composed of 1 (one thousand), 9 (nine hundreds), 0 (zero tens), and 4 (four units). To write the Roman numeral, each of the non-zero digits should be treated separately. Thus 1,000 = M, 900 = CM, and 4 = IV. Therefore, 1904 is MCMIV.
No comments:
Post a Comment