HackerRank The Time in Words Solution

Hello Programmers, In this post, you will know how to solve the HackerRank The Time in Words Solution. This problem is a part of the HackerRank Algorithms Series.

HackerRank The Time in Words Solution
HackerRank The Time in Words Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank The Time in Words Solution

Ezoicreport this adTask

Given the time in numerals we may convert it into words, as shown below:

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

At minutes = 0, use o’ clock. For 1 <= minutes <= 30, use past, and for 30 < minutes use to. Note the space between the apostrophe and clock in oclock. Write a program which prints the time in words for the input given in the format described.

Function Description

Complete the timeInWords function in the editor below.

timeInWords has the following parameter(s):

  • int h: the hour of the day
  • int m: the minutes after the hour

Returns

  • string: a time string as described

Input Format

The first line contains h, the hours portion The second line contains m, the minutes portion

Constraints

  • 1 <= h <= 12
  • 0 <= m < 60

Sample Input 0

5
47

Sample Output 0

thirteen minutes to six

Sample Input 1

3
00

Sample Output 1

three o' clock

Sample Input 2

7
15

Sample Output 2

quarter past seven

HackerRank The Time in Words Solution

The Time in Words Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

char words[][21] = {"o' clock", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty"};

int main() {

    int minutes, hours;
    int half = 0; //0 if minutes are less than 30, 1 if greater than 30
    scanf("%d %d", &hours, &minutes);
    
    if (minutes > 30) {
        minutes = 60-minutes; //to account for the "To"
        half = 1;
    }
    
    if (minutes < 21 && minutes != 15 && minutes != 0 && minutes != 1) {
        printf("%s minutes ", words[minutes]);
    }
    else if (minutes == 1) {
        printf("%s minute ", words[minutes]);
    }
    else if (minutes > 20 && minutes < 30) {
        printf("%s %s minutes ", words[20], words[minutes-20]);
    }
    else if (minutes == 15) {
        printf("quarter ");
    }
    else if (minutes == 30) {
        printf("half ");
    }
    
    if (half && minutes != 0) {
        printf("to %s", words[hours+1]);
    }
    else if (!half && minutes != 0){
        printf("past %s", words[hours]);
    }
    else {
        printf("%s %s", words[hours], words[0]);
    }
            
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    return 0;
}

The Time in Words Solution in Cpp

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

string words[30] = {string("one"),string("two"),string("three"),string("four"),string("five"),string("six"),string("seven"),string("eight"),string("nine"),string("ten"),string("eleven"),string("twelve"),string("thirteen"),string("fourteen"),string("fifteen"),string("sixteen"),string("seventeen"),string("eighteen"),string("nineteen"),string("twenty"),string("twenty one"),string("twenty two"),string("twenty three"),string("twenty four"),string("twenty five"),string("twenty six"),string("twenty seven"),string("twenty eight"),string("twenty nine")};


int main() {
    int H,M;
    cin >> H >> M;
    if (M==0) {
        printf("%s o' clock\n",words[H-1].c_str());
    } else if (M==1) {
        printf("one minute past %s\n",words[H-1].c_str());
    } else if (M==15) {
        printf("quarter past %s\n",words[H-1].c_str());
    } else if (M<30) {
        printf("%s minutes past %s\n",words[M-1].c_str(),words[H-1].c_str());
    } else if (M==30) {
        printf("half past %s\n",words[H-1].c_str());
    } else if (M==45) {
        printf("quarter to %s\n",words[H%12].c_str());
    } else if (M==59) {
        printf("one minute to %s\n",words[H%12].c_str());
    } else {
        printf("%s minutes to %s\n",words[60-M-1].c_str(),words[H%12].c_str());
    }
    
    return 0;
}

The Time in Words Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        String[] numberWords = new String[] {
				"",
				"one",
				"two",
				"three",
				"four",
				"five",
				"six",
				"seven",
				"eight",
				"nine",
				"ten",
				"eleven",
				"twelve",
				"thirteen",
				"fourteen",
				"fifteen",
				"sixteen",
				"seventeen",
				"eighteen",
				"nineteen",
				"twenty",
				"twenty one",
				"twenty two",
				"twenty three",
				"twenty four",
				"twenty five",
				"twenty six",
				"twenty seven",
				"twenty eight",
				"twenty nine"
		};
		
		Scanner in = new Scanner(System.in);
		int hour = in.nextInt();
		int minute = in.nextInt();
		
		int nextHour = (hour % 12) + 1;
		
		if(minute == 0) {
			System.out.printf("%s o' clock\n", numberWords[hour]);
		}
		
		else if(minute == 15) {
			System.out.printf("quarter past %s\n", numberWords[hour]);
		}
		
		else if(minute == 30) {
			System.out.printf("half past %s\n", numberWords[hour]);
		}
		
		else if(minute == 45) {
			System.out.printf("quarter to %s\n", numberWords[nextHour]);
		}
		
		else if(minute < 30) {
			System.out.printf("%s minutes past %s\n", numberWords[minute], numberWords[hour]);
		}
		
		else {
			System.out.printf("%s minutes to %s\n", numberWords[60 - minute], numberWords[nextHour]);
		}
    }
}
Ezoicreport this ad

The Time in Words Solution in Python

# Enter your code here. Read input from STDIN. Print output to STDOUT
H = int(raw_input())
M = int(raw_input())

def word(x):
    unit = ["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]
    dec = ["", "ten", "twenty", "thirty", "forty", "fifty"]
    if x < 20:
        return unit[x]
    return dec[x/10] + " " + unit[x%10]

def minu(x):
    w = word(x)
    if x == 1: return w + " minute"
    else: return w + " minutes"

if M == 0:
    print "{} o' clock".format(word(H))
elif M == 15:
    print "quarter past {}".format(word(H))
elif M == 45:
    print "quarter to {}".format(word(H+1))
elif M == 30:
    print "half past {}".format(word(H))
elif M < 30:
    print "{} past {}".format(minu(M), word(H))
else:
    print "{} to {}".format(minu(60-M), word(H+1))

The Time in Words Solution using JavaScript

var numbers = [
	"zero", "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"];
function processData(input) {
    var datas = input.split('\n');
    var time = +datas[0],
        minute = +datas[1];
    
    var time_str = getMinute(minute) + " " + getTime(time, minute);
    console.log(time_str.trim()); 
} 
function getTime(time, minute) {
    var str = "";
    if(minute>30) {
        str += numbers[(time + 1) % 12];
    } else {
        str += numbers[time]; 
    }
    if(minute==0) {
        str+= " o' clock";
    }
    return str;
}
function getMinute(minute) {
    var str = "";
    var to_min = 0;
    if (minute > 0 && minute <= 30) {
        str = numbers[minute];
        if(minute!=15 && minute!=30) {
            str += " minute" + (minute!=1?"s":"");
        }
        str += " past";
    } else if(minute>30) {
        to_min = 60 - minute;
        str = numbers[to_min];
        if(to_min != 15) {
            str += " minute" + (to_min!=1?"s":"");
        }
        str+=" to";
    }
    return str;
}


process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

The Time in Words Solution in Scala

object Solution {

    def main(args: Array[String]) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution
*/
        val hours = readInt
        val min   = readInt
            
        val numwordsC = Map(
            0 -> "",
            1 -> "one",
            2 -> "two",
            3 -> "three",
            4 -> "four",
            5 -> "five",
            6 -> "six",
            7 -> "seven",
            8 -> "eight",
            9 -> "nine",
            10 -> "ten",
            11 -> "eleven",
            12 -> "twelve",
            13 -> "thirteen",
            14 -> "fourteen",
            15 -> "fifteen",
            16 -> "sixteen",
            17 -> "seventeen",
            18 -> "eighteen",
            19 -> "nineteen",
            20 -> "twenty",
            30 -> "thirty",
            40 -> "forty",
            50 -> "fifty"
        )
            
        def numwords(i: Int) = {
            i match {
                case i: Int if i <= 20 => numwordsC(i)
                case i: Int if i > 20 => {
                   val sup = numwordsC((i / 10) * 10)
                   val sub = numwordsC(i % 10)
                   if(sup != "") s"$sup $sub" else s"$sub"
                }
            }
        }
        def hourfix(i:Int) = {
            val hr = if(i==12) 12 else (i % 12)
            if(hr == 0) 1 else hr
        }
        
        val min0 = "o' clock"
        val min1 = "one minute past"
        val min15 = "quarter past"
        val minspast = "minutes past"
        val min30 = "half past"
        val minto = "minute to"
        val minsto = "minutes to"
        val min45 = "quarter to"
            
        val result = min match {
            case 0 => s"${numwords(hourfix(hours))} $min0"
            case 1 => s"$min1 ${numwords(hourfix(hours))}"
            case 59=> s"${numwords(60 - min)} $minto ${numwords(hourfix(hours+1))}"
            case 15 => s"$min15 ${numwords(hourfix(hours))}"
            case 30 => s"$min30 ${numwords(hourfix(hours))}"
            case 45 => s"$min45 ${numwords(hourfix(hours+1))}"
            case min:Int if min < 30 => s"${numwords(min)} $minspast ${numwords(hourfix(hours))}"
            case min:Int if min > 30 => s"${numwords(60 - min)} $minsto ${numwords(hourfix(hours+1))}"
        }
        
        println(result)
         
    }
}

The Time in Words Solution in Pascal

(* Enter your code here. Read input from STDIN. Print output to STDOUT *)
Program TheTimeInWords;
var H,M: Integer;
const nums:array [0..20] of string = ('0''clock', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'quarter', 'sixteen', 'seventeen', 'eighteen', 'ninteen', 'twenty');
begin
  readln(H);
  readln(M);
  if M > 30 then begin Inc(H); if H = 13 then H := 1; end;
  if M = 0 then writeln(nums[H] + ' o'' clock')
  else if M = 1 then writeln('one minute past ' + nums[H])
  else if M = 15 then writeln('quarter past ' + nums[H])
  else if M <= 20 then writeln(nums[M] + ' minutes past ' + nums[H])
  else if M < 30 then writeln('twenty ' + nums[M - 20] + ' minutes past ' + nums[H])
  else if M = 30 then writeln('half past ' + nums[H])
  else if M < 40 then writeln('twenty ' + nums[40 - M] + ' minutes to ' + nums[H])
  else if M = 45 then writeln('quarter to ' + nums[H])
  else if M < 59 then writeln(nums[60 - M] + ' minutes to ' + nums[H])
  else writeln('one minute to ' + nums[H]);
end.

Disclaimer: This problem (The Time in Words) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Chocolate Feast Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad