samedi 6 mai 2017

Comparing two time values

I have participated in a challenge, in which the requirement is to compare two time values t1 and t2, and print First if t1 occurs before t2 ; otherwise, print Second.

And, t1 != t2.

My code:

import java.util.*;

public class Solution {

    static String timeCompare(String t1, String t2){
        // Complete this function

        String half1 = t1.substring(t1.length()-2);
        String half2 = t2.substring(t2.length()-2);

        String time1 = t1.substring(0, t1.length()-2);
        String time2 = t2.substring(0, t2.length()-2);

        //System.out.println(time1);

        int hour1 = Integer.parseInt(time1.split(":")[0]);
        int hour2 = Integer.parseInt(time2.split(":")[0]);

        int min1 = Integer.parseInt(time1.split(":")[1]);
        int min2 = Integer.parseInt(time2.split(":")[1]);

        if(hour1 == 12) {
            hour1 = 0;
            //System.out.println(hour1);;
        }
        if(hour2 == 12) {
            hour2 = 0;
        }

        //System.out.println(hour1+" , "+hour2);

        if(half1.equals(half2)){
           // System.out.println(1);

            if(hour1 == hour2){

                if(min1 > min2){
                    return "Second";
                } 
                else{
                    return "First";
                }

            }
            else if(hour1 > hour2){
                return "Second";
            }
            else{
                //System.out.println(2);

                return "First";
            }

        }
        else if (half1 == "AM"){
            return "First";
        }
        else{
            return "Second";
        }

    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int q = in.nextInt();
        for(int a0 = 0; a0 < q; a0++){
            String t1 = in.next();
            String t2 = in.next();
            String result = timeCompare(t1, t2);
            System.out.println(result);
        }
    }
}

I am not sure what am I doing wrong. But only 1 out of say, 10 test cases passed.

Sample Input:

2
10:19PM 02:49AM
08:49AM 09:10AM

Sample Output:

Second
First

In this case I am getting the correct answer, but not in the rest of the TCs.

Can you tell what's wrong?

Aucun commentaire:

Enregistrer un commentaire