273. Integer to English Words #247
-
Topics : Convert a non-negative integer Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 273. Integer to English Words <?php
function numberToWords($num) {
if ($num == 0) {
return "Zero";
}
$thousands = ["", "Thousand", "Million", "Billion"];
$index = 0;
$result = "";
while ($num > 0) {
if ($num % 1000 != 0) {
$result = helper($num % 1000) . $thousands[$index] . " " . $result;
}
$num = intval($num / 1000);
$index++;
}
return trim($result);
}
function helper($num) {
$below_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
$tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"];
if ($num == 0) {
return "";
} elseif ($num < 20) {
return $below_20[$num] . " ";
} elseif ($num < 100) {
return $tens[intval($num / 10)] . " " . helper($num % 10);
} else {
return $below_20[intval($num / 100)] . " Hundred " . helper($num % 100);
}
}
// Test cases
echo numberToWords(123) . "\n"; // Output: "One Hundred Twenty Three"
echo numberToWords(12345) . "\n"; // Output: "Twelve Thousand Three Hundred Forty Five"
echo numberToWords(1234567) . "\n"; // Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
?> Explanation:
This solution handles the constraints and edge cases effectively, providing the correct English words representation for any number within the given range. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
Define the words for numbers: We need arrays for the words representing single digits, teens, tens, and the thousands groupings.
Create a helper function: This function will handle numbers less than 1000, converting them to English words.
Recursive function: The main function will recursively process chunks of the number, adding the appropriate thousand group label (e.g., Thousand, Million, Billion).
Edge cases: Handle edge cases like
0
and numbers where intermediate chunks are zero.Let's implement this solution in PHP: 273. Integer to English Words