Convert a non-negative integer to its english words representation.
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
逻辑本身不是太难。这题的特点就是英语是以1000为单位进行操作的,不像汉语用“万”。
英语的另一个特点就是小于20的数字要特殊对待,整十的数字也要特殊对待。
一个数字num, 分为num<20, num<100提取整十,num<1000提取hundreds,再处理剩下小于100的部分。
大于1000的数字,有thuansands, million, billion. 1000以内的按上一行的方法处理。
这里另一个地方就是数字的单词拼写,不出错是很难的,所以多多记忆吧。
public class Solution {
private static final String[] lessThan20 = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
private static final String[] tens = {"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
private static final String[] thousands = {"","Thousand","Million","Billion"};
public String numberToWords(int num) {
if(num == 0) return "Zero";
String word = "";
int i = 0;
while(num > 0){
if(num%1000 != 0){
word = helper(num%1000) + thousands[i] + " " + word;
}
num = num/1000;
i++;
}
return word.trim();
}
public String helper(int n) {
if(n == 0){
return "";
} else if(n<20){
return lessThan20[n] + " ";
} else if(n<100){
return tens[n/10] + " " + helper(n%10);
} else {
return lessThan20[n/100] + " Hundred " + helper(n%100);
}
}
}
12 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[] M = {"","M","MM","MMM"}; // M=1000
String[] C = {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; //C = 100, D= 500
String[] X = {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; // X=10, L =50
String[] I = {"","I","II","III","IV","V","VI","VII","VIII","IX"}; // I= 1, V =5
return M[num/1000]+C[(num%1000)/100] + X[(num%100)/10] + I[(num%10)];
}
}
这样穷举出所有情况的好处,就是不用处理IV这种特殊情况,变得更迅速高效,代码也简洁。
相当于简化版的Integer to English Words.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。