You are viewing a single comment's thread. Return to all comments →
My Java solution with constant space and time complexity:
private static final String[] NUM_WORDS = { "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "quarter", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty one", "twenty two", "twenty three", "twenty four", "twenty five", "twenty six", "twenty seven", "twenty eight", "twenty nine", "half" }; public static String timeInWords(int h, int m) { if(m == 0){ //use o' clock String hour = NUM_WORDS[h]; return hour + " o' clock"; } if(m <= 30){ //use past String minutes; if(m == 1) minutes = "one minute"; else if(m == 15) minutes = "quarter"; else if(m == 30) minutes = "half"; else minutes = NUM_WORDS[m] + " minutes"; String hour = NUM_WORDS[h]; return minutes + " past " + hour; } else{ //use to String minutes; if(60 - m == 1) minutes = "one minute"; else if(60 - m == 15) minutes = "quarter"; else minutes = NUM_WORDS[60 - m] + " minutes"; String hour = NUM_WORDS[(h < 12) ? h + 1 : 1]; return minutes + " to " + hour; } }
Seems like cookies are disabled on this browser, please enable them to open this website
The Time in Words
You are viewing a single comment's thread. Return to all comments →
My Java solution with constant space and time complexity: