Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> “One Hundred Twenty Three”
12345 -> “Twelve Thousand Three Hundred Forty Five”
1234567 -> “One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven”
这道题不难,就是需要细心+耐心。
代码如下:
/*
* 这个题不难
* 就是要细心,注意各种情况的格式的控制输出
* 这里使用的是String,其实使用StringBuilder可能更快
* */
class Solution
{
public String numberToWords(int num)
{
if(num<0)
return "";
if(num==0)
return "Zero";
String[] units = {""," Thousand"," Million"," Billion"};
String res="";
int i=0;
while(num>0)
{
int one=num%1000;
if(one>0)
res = getWords(one) + units[i] + (res.length()==0? "": " "+res);
i++;
num=num/1000;
}
return res;
}
private String getWords(int num)
{
String res = "";
String[] ten = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
String[] hundred = {"Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
String[] twenty = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
if(num/100>0)
{
res = res + ten[num/100]+ " Hundred";
num=num%100;
}
if(num>=10 && num<20)
{
if(res.length()==0)
res=res+twenty[num%10];
else
res=res+" "+twenty[num%10];
return res;
}else if(num>=20)
{
int tmp=num/10;
if(res.length()==0)
res=res+hundred[tmp-1];
else
res=res+" "+hundred[tmp-1];
num=num%10;
}
if(num>0)
{
if(res.length()==0)
res=res+ten[num];
else
res=res+" "+ten[num];
}
return res;
}
}
下面是C++的做法,是一个很烦的做法,代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <algorithm>
using namespace std;
class Solution
{
public:
static string numberToWords(int n)
{
if (n == 0)
return "Zero";
else
return int_string(n).substr(1);
}
static const char * const below_20[];
static const char * const below_100[];
static string int_string(int n)
{
if (n >= 1000000000)
return int_string(n / 1000000000) + " Billion" + int_string(n - 1000000000 * (n / 1000000000));
else if (n >= 1000000)
return int_string(n / 1000000) + " Million" + int_string(n - 1000000 * (n / 1000000));
else if (n >= 1000)
return int_string(n / 1000) + " Thousand" + int_string(n - 1000 * (n / 1000));
else if (n >= 100)
return int_string(n / 100) + " Hundred" + int_string(n - 100 * (n / 100));
else if (n >= 20)
return string(" ") + below_100[n / 10 - 2] + int_string(n - 10 * (n / 10));
else if (n >= 1)
return string(" ") + below_20[n - 1];
else return "";
}
};
const char * const Solution::below_20[] = { "One", "Two", "Three", "Four","Five","Six","Seven","Eight","Nine","Ten", "Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen" };
const char * const Solution::below_100[] = { "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };