Hacker Rank Time Conversion problem solution Easiest
Hacker Rank Time Conversion problem solution Easiest

Hacker Rank Time Conversion problem solution Easiest

In  this HackerRank Time Conversion problem solution, you have given a time in 12 hour AM/PM format, you need to convert it to military (24-hour) time.

Example

  • s = ’12:01:00PM’
    Return ’12:01:00′.
  • s = ’12:01:00AM’
    Return ’00:01:00′.

Hacker Rank Time Conversion problem solution:

Problem solution in Java programming:

public static String timeConversion(String s) {
    // Write your code here
    //String temp = s;
    int hour=Integer.valueOf(s.substring(0, 2));
    if(s.substring(s.length()-2, s.length()).equalsIgnoreCase("AM")){
        hour=hour%12;
    }else{
        hour=(hour%12)+12;
    }
     
     if(hour<10){
         return "0".concat(String.valueOf(hour).concat(s.substring(2, s.length()-2)));
     }else{
         return String.valueOf(hour).concat(s.substring(2, s.length()-2));
     }

Problem solution in Python programming:

def timeConversion(s):
    a = (s[0]+ s[1])
    new_s = s[:-2]
    if s[-2] == "A":
        if a == "12":
            new_s = "00" + (new_s[2:])
            return (new_s)
        return new_s
    else:
        if a == "12":
            return new_s
        a1 = int(a) + 12
        new_s = (str(a1) + (new_s[2:]))
        return (new_s)

Problem solution in C programming:

char* timeConversion(char* s) {
    
    int i = 0;
    int hms[3] = {0};
    char apm[2] = {0};
    char *result = NULL;
    char *token = NULL;
    
    result = (char *)malloc(9);
    memset(result, 0, 9);

    strncpy(apm, &s[8], 2);
    memset(&s[8], 0, 2);  

    token = strtok(s, ":");
    while (token != NULL) {
        hms[i] = atoi(token);
        token = strtok(NULL, ":");
        i++;
    }
    
    if(!strncmp(apm, "PM", 2))
    {
        if(hms[0] != 12)
        {
            hms[0] += 12;
        }
    }
    else if(!strncmp(apm, "AM", 2))
    {
        if(hms[0] == 12)
            hms[0] = 0;
    }
    
    sprintf(result, "%02d:%02d:%02d", hms[0],hms[1],hms[2]);
    
    return result;
}

Problem solution in C# programming:

public static string timeConversion(string s)
    {
		
        DateTime dt=Convert.ToDateTime(s);
				
        return   dt.ToString("HH:mm:ss");
    
		}

Check Also

Caesar Cipher Problem Solution

Caesar Cipher Hacker Rank Solution Best & Easiest

In this post, we will solve the Caesar Cipher HackerRank Solution. This problem (Caesar Cipher) is a …

Leave a Reply

Your email address will not be published. Required fields are marked *