Description:
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"
Solution:
前面没有打这道题目是有点搞不清and应该怎么用,但是刚刚发现竟然不需要写and,难度系数瞬间下降。小模拟。
<span style="font-size:18px;">public class Solution {
public String numberToWords(int num) {
String ans = "";
int tot = 0;
String[] digit = { "", " Thousand", " Million", " Billion" };
while (num > 0) {
if (num % 1000 > 0)
ans = turnToHundred(num % 1000) + digit[tot] + " " + ans;
tot++;
num = num / 1000;
}
ans = ans.trim();
if (ans.equals(""))
ans = "Zero";
return ans;
}
String[] ones = { "", "One", "Two", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen",
"Nineteen" };
String[] tens = { "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty",
"Seventy", "Eighty", "Ninety" };
public String turnToHundred(int num) {
String ans = "";
int one = num % 10;
int ten = num % 100;
int hundred = num / 100;
if (hundred > 0)
ans = ones[hundred] + " Hundred ";
if (ten < 20)
ans = ans + ones[ten];
else
ans = ans + tens[ten / 10] + " " + ones[one];
ans = ans.trim();
return ans;
}
}</span>