rajch

testnumtowords

Mar 9th, 2021
620
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5. )
  6.  
  7. func main() {
  8.     testcases := []int {
  9.         -1,
  10.         1000,
  11.         15,
  12.         64,
  13.         50,
  14.         219,
  15.         998,
  16.         305,
  17.         450,
  18.         900,
  19.     }
  20.    
  21.     for _, testvalue := range testcases {
  22.         result, ok := numbertowords(testvalue)
  23.         fmt.Println(testvalue, result, ok)
  24.        
  25.     }
  26. }
  27.  
  28. func numbertowords(number int) (string, bool) {
  29.     if number<0 || number>999 {
  30.         return "", false
  31.     }
  32.    
  33.     words := [21]string{
  34.             "zero",
  35.             "one",
  36.             "two",
  37.             "three",
  38.             "four",
  39.             "five",
  40.             "six",
  41.             "seven",
  42.             "eight",
  43.             "nine",
  44.             "ten",
  45.             "eleven",
  46.             "twelve",
  47.             "thirteen",
  48.             "fourteen",
  49.             "fifteen",
  50.             "sixteen",
  51.             "seventeen",
  52.             "eighteen",
  53.             "nineteen",
  54.     }
  55.    
  56.     tenwords := [10]string {
  57.         "",
  58.         "",
  59.         "twenty",
  60.         "thirty",
  61.         "forty",
  62.         "fifty",
  63.         "sixty",
  64.         "seventy",
  65.         "eighty",
  66.         "ninety",
  67.     }
  68.    
  69.     result := ""
  70.    
  71.     hundreds := number/100
  72.    
  73.     if hundreds > 0 {
  74.         result = words[hundreds] + " hundred "
  75.         number = number % 100
  76.         if number == 0 {
  77.             return result, true
  78.         }
  79.     }
  80.    
  81.     tens := number / 10
  82.     units := number % 10
  83.    
  84.    
  85.     if tens < 2 {
  86.         return result + words[number], true
  87.     }
  88.    
  89.     if units == 0 {
  90.         return result + tenwords[tens], true
  91.     }
  92.    
  93.     return result + tenwords[tens] + " " + words[units], true
  94.    
  95. }
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×