Algorithm


Problem Name: Algorithms - Time Conversion

Problem Link: https://www.hackerrank.com/challenges/time-conversion/problem?isFullScreen=true

In this HackerRank Functions in Algorithms - Java programming problem solution,

Given a time in 12-hour AM/PM format, convert it to military (24-hour) time.

Note: – 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock.

– 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock.

Example

  • s = ‘12:01:00PM’

Return ’12:01:00′.

  • s = ‘12:01:00PM’

Return ’00:01:00′.

Function Description

Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.

timeConversion has the following parameter(s):

  • string s: a time in 12 hour format

Returns

  • string: the time in 24 hour format

Input Format

A single string s that represents a time in 12-hour clock format (i.e.:hh:mm:ssAM  or hh:mm:ssPM).

Constraints

  • All input times are valid

Sample Input 0

07:05:45PM

Sample Output 0

19:05:45

 

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


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

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    char timestamp[11] = "\0\0\0\0\0\0\0\0\0\0\0";
    int hr = 0;
    
    scanf("%s", timestamp);
    
    if(timestamp[8] == 'P'){
        hr = 10 * (timestamp[0] - '0') + (timestamp[1] - '0');
        if(hr < 12) hr += 12;
    }
    else{
        hr = 10 * (timestamp[0] - '0') + (timestamp[1] - '0');
        if(hr == 12) hr = 0;
    }
    
    timestamp[0] = hr / 10 + '0';
    timestamp[1] = hr % 10 + '0';
    timestamp[8] = '\0';
    timestamp[9] = '\0';
    
    printf("%s", timestamp>;
    return 0;
}
Copy The Code & Try With Live Editor

#2 Code Example with C++ Programming

Code - C++ Programming


#include <cmath>
#include <cstdio>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
string print(int h){
    if(h < 10) return "0" + to_string(h);
    else return to_string(h);
}

int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int h , m , s;
    string str;
    char r;
    cin >> h >> r >> m >> r >> s >> str;
    if(str == "PM" &&  h != 12) h = h + 12;
    else if(str == "AM" && h == 12) h = (h + 12)% 24;
    cout << print(h) << ":" << print(m) << ":" << print(s> << endl;
    return 0;
}
Copy The Code & Try With Live Editor

#3 Code Example with Java Programming

Code - Java Programming


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

public class Solution {

    /*
     * Complete the timeConversion function below.
     */
    static String timeConversion(String s) {
     if(s.charAt(8) == 'P'){

        String portion = s.substring(0,8);
        String[] times = portion.split(":");
        if(times[0].matches("12")){
            return times[0] + ":" + times[1] + ":" + times[2];
        }
        times[0] = String.valueOf(Integer.valueOf(times[0]) + 12);
        return times[0] + ":" + times[1] + ":" + times[2];
     }else{
         String portion = s.substring(0,8);
        String[] times = portion.split(":");
        if(times[0].matches("12")){
            times[0]= "00";
            return times[0] + ":" + times[1] + ":" + times[2];
        }
         return s.substring(0,8);
     }
    }

    private static final Scanner scan = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        String s = scan.nextLine();

        String result = timeConversion(s);

        bw.write(result);
        bw.newLine();

        bw.close();
    }
}
Copy The Code & Try With Live Editor

#4 Code Example with PHP Programming

Code - PHP Programming


Copy The Code & Try With Live Editor

#5 Code Example with C# Programming

Code - C# Programming


using System;
using static System.Console;

class Solution
{
    static void Main(String[] args)
    {
        var time = ReadLine();
        var amOrPm = time.Substring(8);
        var hourComponent = time.Substring(0, 2);
        var remainingTimeComponent = time.Substring(2, 6);
        if (amOrPm == "AM" && hourComponent == "12")
        {
            hourComponent = "00";
        }
        else if (amOrPm == "PM")
        {
            var numericHourComponent = int.Parse(hourComponent);
            if (numericHourComponent != 12)
            {
                hourComponent = Convert.ToString(12 + numericHourComponent);
            }
        }
        WriteLine(hourComponent + remainingTimeComponent);
    }
}
Copy The Code & Try With Live Editor

#6 Code Example with Python Programming

Code - Python Programming


import os
import sys

def timeConversion(s):
    time = s.split(":")
    if s[-2:] == "PM":
        if time[0] != "12":
            time[0] = str(int(time[0])+12)
    else:
        if time[0] == "12":
            time[0] = "00"
    ntime = ':'.join(time)
    return str(ntime[:-2])
    
if __name__ == '__main__':
    f = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = timeConversion(s)

    f.write(result + '\n')

    f.close()
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Birthday Cake Candles in C, C++,Java, JavaScript, Python, PHP & C# solution in Hackerrank
Next
[Solved] Grading Students in C, C++,Java, JavaScript, Python, PHP & C# solution in Hackerrank