<span style="font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; background-color: rgb(255, 255, 255);">273. Integer to English Words</span>
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:
It's a super easy problem. Just make sure you have every detail checked.
(Forgot to install a Chinese language input, sorry
Here is my code.
class Solution {
public:
string num[9] = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"};
string teens[10] = {"Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
string tens[8] = {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
string units[4] = {"", "Thousand", "Million", "Billion"};
string under_1000(int x) {
string ans;
int hun = x / 100;
int ten = (x % 100) / 10;
int sig = x % 10;
bool first = true;
if (hun) {
ans += num[hun - 1] + " Hundred";
first = false;
}
if (ten) {
if (ten >= 2) {
if (!first)
ans += ' ';
ans += tens[ten - 2];
if (sig)
ans += ' ' + num[sig - 1];
first = false;
} else {
if (!first)
ans += ' ';
ans += teens[sig];
}
} else {
if (sig) {
if (!first)
ans += ' ';
ans += num[sig - 1];
}
}
return ans;
}
string numberToWords(int num) {
string ans; int count = 0;
if (!num)
return "Zero";
while (num) {
if (num % 1000 != 0) {
string str = under_1000(num % 1000);
if (str != "")
if (ans != "")
ans = str + ' ' + units[count] + ' ' + ans;
else
if (units[count] != "")
ans = str + ' ' + units[count];
else ans = str;
}
num /= 1000;
++ count;
}
return ans;
}
};
本文介绍了一种将非负整数转换为英文表述的方法。通过详细的代码实现,展示了如何处理千位以上的数值,并确保结果符合英语语法规范。

3987

被折叠的 条评论
为什么被折叠?



