Ordinal Number (1st, 2nd, 3rd)
Problem
Read a positive whole number n and print it with its English ordinal ending: 1st, 2nd, 3rd, 4th ... Numbers that end in 11, 12 or 13 use th (11th, 12th, 13th, 111th). Other numbers that end in 1, 2 or 3 use st, nd or rd.
Constraints
- 1 <= n <= 10^9
Examples
Input
22
Output
22nd
Input
111
Output
111th
Solutions
The special case (11, 12, 13) must be checked before the last digit, because 11 ends in 1 but is 11th, not 11st. This kind of rule appears in all text formatting code.
/*
* Problem : Add the suffix.
* Input : One integer n.
* Output : n with its suffix.
* Approach: Conditions.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static String solve(long n) {
// Step 1: Numbers whose last two digits are 11 to 13 always use "th".
long lastTwo = n % 100;
if (lastTwo >= 11 && lastTwo <= 13) {
return n + "th";
}
// Step 2: For all other numbers, look at the last digit only.
long lastDigit = n % 10;
if (lastDigit == 1) {
return n + "st";
}
if (lastDigit == 2) {
return n + "nd";
}
return n + (lastDigit == 3 ? "rd" : "th");
}
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
System.out.println(solve(n));
}
}
Hints (1)
- Why must 12 be checked before the last digit?