Ad
Fundamentals
Code
Diff
  • function getOrdinalPosition(n: number):string{
     //check when less than 0 throw err
      if(n < 0)
        throw new Error("Should be a positive number");
      
      //define suffix contain ordinary
      const suffixes = ["th", "st", "nd", "rd"]
      
      //get remain number by module 100
      const lastTwoDigits = n % 100;
      
      //if n between 11 and 13, ordinal number would be `th`
      if(n >= 11 && n <= 13)
        return n + 'th';
      
      //Otherwise, we take the last digit and use it to index into the suffixes array
      const lastDigit = n % 10;
      const suffix = suffixes[lastDigit] || "th"
      
      return n + suffix;
    }
    
    console.log(getOrdinalPosition(21));
    console.log(getOrdinalPosition(76));
    console.log(getOrdinalPosition(33));
    console.log(getOrdinalPosition(987654321))
    console.log(getOrdinalPosition(12345))
    console.log(getOrdinalPosition(9999))
    • class OrdinalNumbers:
    • def __init__(self, n):
    • self.n = n
    • def solution(self):
    • pass
    • function getOrdinalPosition(n: number):string{
    • //check when less than 0 throw err
    • if(n < 0)
    • throw new Error("Should be a positive number");
    • //define suffix contain ordinary
    • const suffixes = ["th", "st", "nd", "rd"]
    • //get remain number by module 100
    • const lastTwoDigits = n % 100;
    • //if n between 11 and 13, ordinal number would be `th`
    • if(n >= 11 && n <= 13)
    • return n + 'th';
    • //Otherwise, we take the last digit and use it to index into the suffixes array
    • const lastDigit = n % 10;
    • const suffix = suffixes[lastDigit] || "th"
    • return n + suffix;
    • }
    • console.log(getOrdinalPosition(21));
    • console.log(getOrdinalPosition(76));
    • console.log(getOrdinalPosition(33));
    • console.log(getOrdinalPosition(987654321))
    • console.log(getOrdinalPosition(12345))
    • console.log(getOrdinalPosition(9999))