題目描述

給定一個用數字表示的時間,將其轉成使用英文單字來表式。



5:00 → five o' clock
5:01 → one minute past five
5:10 → ten minutes past five
5:28 → twenty eight minutes past five
5:30 → half past five
5:40 → twenty minutes to six
5:45 → quarter to six
5:47 → thirteen minutes to six

請寫出一個可以進行如以上時間格式轉換的程式。

原題網址

https://www.hackerrank.com/challenges/the-time-in-words

輸入格式

輸入有兩行。第一行為小時H,範圍在1到12之間(包含1和12)。第二行為分鐘M,範圍在0到60之間(包含0和60)。

輸出格式

輸出用英文來表示時間的結果。

範例輸入

5
47

範例輸出

thirteen minutes to six

解題概念

可用字串陣列儲存數字的英文單字,再用if-else if-else結構來判斷分鐘的數值範圍,來決定要套用哪種英文時間格式。

參考答案

import java.util.Scanner;

public class Solution {

    private static final String[] NUMBER = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"};
    private static final String[] NUMBER2 = {"twenty", "thirty", "fourty", "fifty"};

    private static String numberToString(int n) {
        if (n >= 20) {
            return String.valueOf(NUMBER2[n / 10 - 2]).concat(" ").concat(NUMBER[n % 10]);
        } else {
            return String.valueOf(NUMBER[n]);
        }
    }

    public static void main(String[] args) {
        final Scanner sc = new Scanner(System.in);
        final int H = sc.nextInt(), M = sc.nextInt();

        if (M == 0) {
            System.out.println(numberToString(H).concat(" o' clock"));
        } else if (M == 1) {
            System.out.println("one minute past ".concat(numberToString(H)));
        } else if (M == 15) {
            System.out.println("quarter past ".concat(numberToString(H)));
        } else if (M < 30) {
            System.out.println(numberToString(M).concat(" minutes past ").concat(numberToString(H)));
        } else if (M == 30) {
            System.out.println("half past ".concat(numberToString(H)));
        } else if (M == 45) {
            System.out.println("quarter to ".concat(numberToString(H + 1)));
        } else if (M == 59) {
            System.out.println("one minute to ".concat(numberToString(H + 1)));
        } else {
            System.out.println(numberToString(60 - M).concat(" minutes to ").concat(numberToString(H + 1)));
        }
    }
}