john sokpo

Generation

generate functionThu, 06 Jul 2023

Convert a non-negative integer num to its English words representation. Example 1: Input: num = 123 Output: "One Hundred Twenty Three" Example 2: Input: num = 12345 Output: "Twelve Thousand Three Hundred Forty Five" Example 3: Input: num = 1234567 Output: "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"

public class Solution { public String numberToWords(int num) { if (num == 0) return "Zero"; String res = ""; int count = 0; while (num > 0) { int digit = num % 1000; num /= 1000; String tmp = helper(digit); res = tmp + " " + units[count] + " " + res; count++; } return res.trim(); } private String helper(int num) { if (num == 0) return ""; String res = ""; if (num / 100 > 0) { res = digits[num / 100] + " Hundred "; num %= 100; } if (num / 10 > 1) { res += tens[num / 10] + " "; num %= 10; } else if (num / 10 == 1) { res += teens[num % 10] + " ";

Want to kickstart your project?Use the new AI Studio to create your code