原题如下
https://leetcode-cn.com/problems/english-int-lcci/
题解
/*
*@v7fgg
*执行用时 :17 ms, 在所有 Java 提交中击败了27.86%的用户
*内存消耗 :39.8 MB, 在所有 Java 提交中击败了100.00%的户
*2020年6月18日 22:24
*/
class Solution {
public String numberToWords(int num) {
//考虑特殊情况的0
if(num==0){return "Zero";}
String ans="";
//原数字在后面还要用到,因此复制一份,这里只需要考虑绝对值
int m=Math.abs(num);
int yi=m%1000;//1000以内的值,也就是后三位
int qian=m/1000%1000;//多少千thousand
int baiwan=m/1000000%1000;//多少百万million
int shiyi=m/1000000000;//多少十亿billion
if(yi>0){
ans=in1000(yi);
}
if(qian>0){
ans=in1000(qian)+" Thousand "+ans;
}
if(baiwan>0){
ans=in1000(baiwan)+" Million "+ans;
}
if(shiyi>0){
ans=in1000(shiyi)+" Billion "+ans;
}
//考虑负数的情况
if(num<0){ans="Negative "+ans;}
return ans.trim();
}
public String in1000(int a){
//此函数是把一个1000以内的数字变成字符串
String shuzi1[]=new String[]{"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
String shuzi2[]=new String[]{"","Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
String r="";
if(a%100<20){
r=shuzi1[a%100];
a/=100;
}
else{
r=shuzi1[a%10];
a/=10;
if(a>0){
//要去掉空格,因为会出现比如:3000000 thirty thousand
r=(shuzi2[a%10]+" "+r).trim();
a/=10;
}
}
if(a>0){
//去空格是因为会出现比如:100000 one hundred thousand
r=(shuzi1[a]+" Hundred "+r).trim();
}
return r;
}
}