273.|273. Integer to English Words
【273.|273. Integer to English Words】Hard
找的LC上比较满意的答案了,一开始建立一个 LESS_THAN_20和TENS的String array来装常量。然后分为num < 20
, num < 100
, num < 1000
, num < 1000000
, num < 100000000
来分类。注意一下 +” Hundred "
这些都需要前后留一个空格. 还有为什么两个array里要放一个""
元素。是为了index可以配合数据,比如TENS[1]是Ten, TENS[2] = Twenty. 注意下billion是十亿不是一亿哦。
class Solution {
private final String[] LESS_THAN_20 = {"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven",
"Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
private final String[] TENS = {"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
public String numberToWords(int num) {
if (num == 0){
return "Zero";
}
return helper(num);
}private String helper(int num){
String res = "";
if (num < 20){
res = LESS_THAN_20[num];
} else if (num < 100){
res = TENS[num / 10] + " " + helper(num % 10);
} else if (num < 1000){
res = helper(num / 100) + " Hundred " + helper(num % 100);
} else if (num < 1000000){
res = helper(num / 1000) + " Thousand " + helper(num % 1000);
} else if (num < 1000000000){
res = helper(num / 1000000) + " Million " + helper(num % 1000000);
} else {
res = helper(num / 1000000000) + " Billion " + helper(num % 1000000000);
}
return res.trim();
}
}
推荐阅读
- 029|029 Divide Two Integers
- English|Buffett-Backed BYD May Develop In-House Chip to Improve Intelligent Driving
- English|Chinese Fast Fashion Brand SHEIN Seeks to Float IPO in the U.S. in 2024
- English|MINISO Launches Secondary Listing in Hong Kong
- English|China's Economy Grows 0.4 Percent in Second Quarter
- English|TSMC Beats Profit Estimates with New Record but Expects Decline in Chip Demand
- English|WPS to Halt its Advertising Business Next Year
- English|360 Sees Net Profit Down in the First Half of 2022
- English|Alibaba Downsizes its Strategic Investment Unit
- English|Alibaba's Freshippo Said to Cut Valuation by 40% in Seven Months