Integer to something 类型题总结

Integer to something 类型题总结

这种类型题的思路就是将可能的情况放到Array中,由小到大或者由大到小排列,将需要得到的结果依次减Array中的index得出结果。之前做过的Broadway Technology的OA也是同样类型的题。

  1. Integer to Roman:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public String intToRoman(int num) {
int[] romanNumber = new int[]{1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
String[] strs = new String[]{"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};

String ans = "";
int index = romanNumber.length-1;
while(num>0){
if(romanNumber[index]>num){
index--;
continue;
}
else {
num = num - romanNumber[index];
ans = ans + strs[index];
}
}
return ans;

}
}

  1. Integer to English Words

这道题的思想其实与罗马数字也类似,但不同点在于罗马数字是不停地减,这种需要不停地取余,相当于从高位到低位依次处理。
分析这道题的时候,关键是发现:数字在西方是以1000为进制的,所以最基本的处理是针对1000来操作,1000以上的数只需要在1000的基础上稍加处理。所以如果是处理中文的话,进制是一万。

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
public String numberToWords(int num) {
if(num==0)
return "Zero";
String ans = "";
while(num>0){
if(num>=1000000000){
int billionNum = num/1000000000;
ans = ans + computeNumLessThousand(billionNum) + "Billion ";
num = num % 1000000000;
}
else if(num>=1000000){
int millionNum = num/1000000;
ans = ans + computeNumLessThousand(millionNum) + "Million ";
num = num % 1000000;
}
else if(num>=1000){
int thousandNum = num/1000;
ans = ans + computeNumLessThousand(thousandNum) + "Thousand ";
num = num % 1000;
}
else{
ans = ans + computeNumLessThousand(num);
break;
}
}
ans = ans.substring(0, ans.length()-1);
return ans;

}

private String computeNumLessThousand(int num){
String[] digits = new String[]{"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
String[] tens = new String[]{"", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
String ans = "";
while(num>0){
if(num>=100){
int hundredNum = num/100;
ans = ans + computeNumLessThousand(hundredNum) + "Hundred ";
num = num %100;
}
else if(num>=20){
int tensNum = num/10;
ans = ans + tens[tensNum] + " ";
num = num %10;
}
else {
ans = ans + digits[num] + " ";
break;
}
}
return ans;
}
}