给定一个整数,打印该整数的英文描述。
示例 1:
输入: 123
输出: "One Hundred Twenty Three"
示例 2:
输入: 12345
输出: "Twelve Thousand Three Hundred Forty Five"
示例 3:
输入: 1234567
输出: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
示例 4:
输入: 1234567891
输出: "One Billion Two Hundred Thirty Four Million Five Hundred Sixty Seven Thousand Eight Hundred Ninety One"
分析:
方法:分治算法
英语的表示和汉语不同,它是隔着三位数表示,比如 "Thousand", "Million", "Billion",因此我们只需要将数字按三位分别进行添加英文即可,因为整形最大为 2147483647,刚好最高位就在 Billion 上,如果数字刚好在该位上,直接判断即可。我们可以将个位,十位,千位分别创建数组方便操作。
时间复杂度:O(1) 取决于数字的位数
空间复杂度:O(1)
class Solution {
//英文
private static String[] ones = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
private static String[] tens = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
private static String[] trous = {"Thousand", "Million", "Billion"};
private static int[] nums = {1000, 1000000, 1000000000};
public String numberToWords(int num) {
//0
if(num == 0){
return "Zero";
}
//结果
StringBuilder sb = new StringBuilder();
//1000 000 000
if(num / nums[2] > 0){
sb.append(ones[num / nums[2]]);
sb.append(" ").append(trous[2]);
num %= nums[2];
}
//1000 000
if(num / nums[1] > 0){
translate(num / nums[1], sb);
sb.append(" ").append(trous[1]);
num %= nums[1];
}
//1000
if(num / nums[0] > 0){
translate(num / nums[0], sb);
sb.append(" ").append(trous[0]);
num %= nums[0];
}
translate(num, sb);
return sb.toString().trim();
}
//对一个千位数进行翻译
public void translate(int num, StringBuilder sb){
//百位
if(num / 100 > 0){
sb.append(" ").append(ones[num / 100]).append(" ").append("Hundred");
num %= 100;
}
//十位
if(num / 10 > 1){
sb.append(" ").append(tens[num / 10]);
num %= 10;
}
//个位
if(num > 0){
sb.append(" ").append(ones[num]);
}
}
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/english-int-lcci