We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static String timeConversion(String s) {
int n = s.length();
String period = s.substring(n - 2); // Extract AM or PM
int hour = Integer.parseInt(s.substring(0, 2)); // Extract hour part
String minAndSec = s.substring(2, n - 2); // Extract minutes and seconds
// Convert the hour based on the period (AM/PM)
if (period.equals("AM")) {
if (hour == 12) {
hour = 0; // Midnight case: 12 AM -> 00 in 24-hour format
}
} else {
if (hour != 12) {
hour += 12; // Afternoon/evening case: convert PM hour to 24-hour format
}
}
// Format and return the converted time
return String.format("%02d%s", hour, minAndSec);
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Time Conversion
You are viewing a single comment's thread. Return to all comments →
public static String timeConversion(String s) { int n = s.length(); String period = s.substring(n - 2); // Extract AM or PM int hour = Integer.parseInt(s.substring(0, 2)); // Extract hour part String minAndSec = s.substring(2, n - 2); // Extract minutes and seconds
}