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.
publicstaticStringtimeConversion(Strings){// Extract the hour from the stringinthour;if(s.charAt(2)==':'){hour=Integer.parseInt(s.substring(0,2));// If there is a colon in the string, then the hour is extracted from the first two characters}else{hour=Integer.parseInt(s.substring(0,1));// Otherwise, the hour is extracted from the first character}// Check for AM/PM and convert the hourStringresult;intnewHour;if(s.charAt(8)=='P'||s.charAt(7)=='P'){// If the string contains 'P', then it is PMnewHour=hour==12?12:hour+12;// If the hour is 12, then leave it as is, otherwise add 12}else{newHour=hour==12?0:hour;// If it's not PM and the hour is 12, then set it to 0, otherwise leave it as is}result="%02d:%s".formatted(newHour,s.charAt(2)==':'?s.substring(3,s.length()-2):s.substring(2,s.length()-2));// Format the result by adding leading zeros to the hour and returning the remaining part of the string after extracting the hourreturnresult;}
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 →
Java