Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solution {
- private readonly string[] LESS_THAN_TWENTY = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"};
- private readonly string[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"};
- private readonly string[] THOUSANDS = {"", "Thousand", "Million", "Billion"};
- public string NumberToWords(int num) {
- if (num == 0) return "Zero";
- string word = string.Empty;
- int i = 0;
- while(num > 0) {
- if (num % 1000 > 0) {
- word = Helper(num %1000) + THOUSANDS[i] + " " + word;
- }
- num /= 1000;
- i++;
- }
- return word.Trim();
- }
- private string Helper(int num) {
- if (num == 0) return "";
- else if (num < 20) return LESS_THAN_TWENTY[num] + " ";
- else if (num < 100) return TENS[num /10] + " " + Helper(num%10);
- return LESS_THAN_TWENTY[num/100] + " Hundred " + Helper(num%100);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement