My accepted C# answer with lookup table


  • 0
    L

    Considering number like this:
    1
    1,000
    1,000,000
    1,000,000,000

    Two function:

    1. Get 2 digit string as value less than 20 have his own word, also for the tens.

    2. For value in hundreds just need 1 to 9.
      Steps:

    3. in the loop Every time get 3 digit.

    4. Check current string for 3 digit. Add non-Zero value + mask or keep the same as before.

    5. check for the next until 0.

      public class Solution
      {

       string[] nums = "Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};
       string[] tensNum = {"Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};
       string[] weiNum = {"","Thousand","Million","Billion"};
       
       public string NumberToWords(int num) {
           if(num==0) return "Zero";
           int wei = 0;
           string result = string.Empty;
           do
           {
               string current = GetThreeIntString(num%1000);
               result = (current == "Zero"?result:(current + " "+weiNum[wei]+" " + result)).Trim();
               num/=1000;
               wei++;
           }while(num>0);
           return result.Trim();
       }
       
       private string GetTwoIntString(int result)
       {
           if(result<=19) return nums[result];
           
           return (tensNum[(result/10) -2]+" "+(nums[result%10]!="Zero"?nums[result%10]:string.Empty)).Trim();
       }
       
       private string GetThreeIntString(int hundred)
       {
           if(hundred/100 == 0) return GetTwoIntString(hundred);
           string twoChar = GetTwoIntString(hundred%100);
           
           return (nums[hundred/100] + " Hundred " + (twoChar!="Zero"?twoChar:string.Empty)).Trim();
       }
      

      }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.