Skip to main content

273 Integer to English Words

Leetcode

Convert a non-negative integer num to its English words representation.

Example 1:

Input: num = 123
Output: "One Hundred Twenty Three"

Example 2:

Input: num = 12345
Output: "Twelve Thousand Three Hundred Forty Five"

Example 3:

Input: num = 1234567
Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"


解法如下。尝试了 10 次才成功。。。

class Solution {
String[] IN_TEN = {
"","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"
};

String[] IN_TWENTY = {
"Eleven","Twelve","Thirteen","Fourteen","Fifteen",
"Sixteen","Seventeen","Eighteen","Nineteen","Twenty"
};

String[] IN_HUNDRED = {
"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"
};

public String numberToWords(int num) {
if(num==0) return "Zero";
return helper(num).trim();
}

private String helper(int num){

if(num==0) return "";

if(num<=10) return IN_TEN[num];

if(num<=20) return IN_TWENTY[num-11];

if(num<100) {
int i1 = num/10;
int i2 = num%10;
if(i2==0) return IN_HUNDRED[i1-2];
return IN_HUNDRED[i1-2]+ " " + IN_TEN[i2];
}

if(num<1000){
int i1 = num/100;
int i2 = num%100;
if(i2==0) return IN_TEN[i1] + " Hundred";
return IN_TEN[i1] + " Hundred " + helper(i2);
}

if(num<1_000_000){
int i1=num/1000;
int i2=num%1000;
if(i2==0) return helper(i1)+" Thousand";
return helper(i1)+" Thousand "+helper(i2);
}

if(num<1_000_000_000){
int i1=num/1_000_000;
int i2=num%1_000_000;
if(i2==0) return helper(i1)+" Million";
return helper(i1)+" Million "+helper(i2);
}

int i1=num/1_000_000_000;
int i2=num%1_000_000_000;
if(i2==0) return helper(i1)+" Billion";
return helper(i1)+" Billion "+helper(i2);

}
}