Revision 1f4bf4d1-77c3-4f48-8dcd-9759548e9a7d - Code Golf Stack Exchange

# JavaScript, 64 characters (ES3) or 47 characters (ES6)

### ES3 (64 characters):

`function(n){return n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'}`

### ES6 (47 characters):

`n=>n+=[,'st','nd','rd'][n%100>>3^1&&n%10]||'th'`

### Explanation

The expression `n % 100 >> 3 ^ 1` evaluates to 0 for any positive `n` ending with digits `08`–`15`. Thus, for any `n mod 100` ending in `11`, `12`, or `13`, the array lookup returns `undefined`, leading to a suffix of `th`.

For any positive `n` ending in other digits than `08`–`15`, the expression `n % 100 >> 3 ^ 1` evaluates to a positive integer, invoking the expression `n % 10` for array lookup, returning `st`,`nd`, or `rd` for `n` which ends with `1`, `2`, or `3`. Otherwise, `th`.

AltStyle によって変換されたページ (->オリジナル) /