[英]Java - 12 H to 24 Hour Format (hackerrank)
Note : I looked as much as I could for 2 days to check if this is a duplicate.注意:我尽可能多地看了 2 天,以检查这是否是重复的。 If I missed something, I apologize.如果我错过了什么,我道歉。 This question is to find what the issue is with my attempt at a solution, not one of the existing solutions out there.这个问题是为了找出我尝试解决方案时出现的问题,而不是现有的解决方案之一。
My Question我的问题
I was trying to solve some problems on hackerrank in Java 7 and I came across the time conversion problem where the problem statement is:我试图解决 Java 7 中关于hackerrank 的一些问题,但我遇到了时间转换问题,其中问题陈述是:
Problem: "Given a time in -hour AM/PM format, convert it to military (24-hour) time."问题: “给定一个 -hour AM/PM 格式的时间,将其转换为军事(24 小时)时间。”
Sample Input 07:05:45PM样本输入07:05:45PM
Sample Output 19:05:45示例输出19:05:45
I looked at solutions involving libraries (such as java.text.SimpleDateFormat, Calendar etc.) but I am trying to do it on my own without them.我查看了涉及库的解决方案(例如 java.text.SimpleDateFormat、Calendar 等),但我试图在没有它们的情况下自己完成。 The issue that I am facing here is that my solution is failing on some test cases but is working on others.我在这里面临的问题是我的解决方案在某些测试用例上失败,但在其他测试用例上有效。 In short, it is not the correct solution.简而言之,这不是正确的解决方案。 I see other solutions but I want to know why mine fails as the correct answer.我看到了其他解决方案,但我想知道为什么我的解决方案失败了。 Could you please help me by telling me where this would fail and how I can go about correcting it?你能告诉我这会在哪里失败以及我如何纠正它来帮助我吗?
Some of the solutions that I looked at are:我查看的一些解决方案是:
Conversion from 12 hours time to 24 hours time in java java中从12小时制到24小时制的转换
Convert 12 hours to 24 hours 将 12 小时转换为 24 小时
My code is here:我的代码在这里:
import java.io.*;
import java.math.*;
import java.text.*;
import java.util.*;
import java.util.regex.*;
public class Solution {
static String timeConversion(String s) {
//get the string into an array using : as a separator
String[] time_array = s.split(":");
//military_time variable to be returned
String military_time = new String();
//final HH part
String hh_final = new String();
//Rest after HH to be concatenated to get military_time
String rest = new String();
StringBuilder REST_mil_builder = new StringBuilder();
for (int i = 2; i < 8; i++) {
REST_mil_builder.append(s.charAt(i));
}
//"rest" basically gets everything after HH excluding AM/PM, so 01:03:40PM would have a "rest" value of ":03:40"
rest = REST_mil_builder.toString();
int hh = Integer.parseInt(time_array[0]);
String AMPM_contains = time_array[2];
//converting if the last piece after the split contains "PM"
if (AMPM_contains.contains("PM")) {
hh = hh + 12;
hh = hh == 24 ? 0 : hh;
}
//converting hh to have a 0 before it because when it is an integer 01 will be just 1 which we don't want
StringBuilder hh_build = new StringBuilder();
if (hh >= 0 && hh <= 9) {
hh_build.append("0");
hh_build.append(hh);
hh_final = hh_build.toString();
} else {
hh_build.append(hh);
hh_final = hh_build.toString();
}
//military time concatenation
military_time = hh_final + rest;
//Midnight is 12:00:00AM on a 12-hour clock, and 00:00:00 on a 24-hour clock
military_time = s == "12:00:00AM" ? "00:00:00" : military_time;
//Noon is 12:00:00PM on a 12-hour clock, and 12:00:00 on a 24-hour clock.
military_time = s == "12:00:00PM" ? "12:00:00" : military_time;
return military_time;
}
private static final Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
//tried several 12 hour time formats here
String result = timeConversion("01:30:59PM");
System.out.println(result);
}
}
Your code fails because it doesn't correctly handle hour 12, ie 12:xx:xxAM
should map to 00:xx:xx
, and 12:xx:xxPM
should map to 12:xx:xx
, as pointed out in answer by Ole VV您的代码失败是因为它没有正确处理 12 小时,即12:xx:xxAM
应该映射到00:xx:xx
,而12:xx:xxPM
应该映射到12:xx:xx
,正如Ole在回答中指出的那样VV
Rather than trying to fix the overly complicated code you have, here is a different approach, without using SimpleDateFormat
.与其尝试修复您拥有的过于复杂的代码,不如采用一种不同的方法,而不使用SimpleDateFormat
。
Parse the first 2 digits to a number.将前 2 位数字解析为一个数字。 If the number is 12, set it to 0. A trick way to do that is to use modulo 12. If input ends with PM
, add 12. Now rebuild string, replacing first 2 digits with new number, and removing AM/PM suffix.如果数字是 12,则将其设置为 0。一种巧妙的方法是使用模 12。如果输入以PM
结尾,则添加 12。现在重建字符串,用新数字替换前 2 位数字,并删除 AM/PM 后缀.
Like this:像这样:
public static String timeConversion(String s) {
int hour = Integer.parseInt(s.substring(0, 2)) % 12;
if (s.endsWith("PM"))
hour += 12;
return String.format("%02d", hour) + s.substring(2, 8);
}
Using tests by Ole VV使用 Ole VV 的测试
System.out.println(timeConversion("12:30:59AM"));
System.out.println(timeConversion("11:30:59AM"));
System.out.println(timeConversion("12:30:59PM"));
System.out.println(timeConversion("11:30:59PM"));
Output输出
00:30:59
11:30:59
12:30:59
23:30:59
System.out.println(timeConversion("12:30:59AM"));
System.out.println(timeConversion("11:30:59AM"));
System.out.println(timeConversion("12:30:59PM"));
System.out.println(timeConversion("11:30:59PM"));
Expected output:预期输出:
00:30:59
11:30:59
12:30:59
23:30:59
Observed output:观察到的输出:
12:30:59 (wrong)
11:30:59 (correct)
00:30:59 (wrong)
23:30:59 (correct)
Edit: In short it seems your code doesn't take into account that hour 12 is different nn the 12 hour clock.编辑:简而言之,您的代码似乎没有考虑到 12 小时与 12 小时时钟不同。 You may say it's used as hour 00. I don't think it will be too hard to fix your program, so I will let you have the pleasure of the first shot.你可能会说它被用作00小时。我认为修复你的程序不会太难,所以我会让你享受第一枪的乐趣。 If you need a hint, please follow up in comments.如果您需要提示,请在评论中跟进。 We're all happy to help.我们都很乐意提供帮助。
As an aside, you are using new String()
in three places in your code.顺便说一句,您在代码中的三个地方使用了new String()
。 I think it's superfluous because you are never using the created empty strings for anything.我认为这是多余的,因为您永远不会将创建的空字符串用于任何事情。
Please try this static String timeConversion(String s) function
.I hope this will help you.请尝试这个static String timeConversion(String s) function
。我希望这会对你有所帮助。
static String timeConversion(String s) {
String[] time = s.split(":");
String hours = time[0];
String minutes = time[1];
String seconds = time[2].substring(0, 2);
String dayEve = time[2].substring(2, 4);
if (dayEve.equals("AM")) {
return ((hours.equals("12") ? "00" : hours) + ":" + minutes + ":" + seconds);
} else {
return ((hours.equals("12") ? hours : (Integer.parseInt(hours) + 12)) + ":" + minutes + ":" + seconds);
}
}
The prime logic is :-主要逻辑是:-
If 'AM' and hours == 12
then hours set to 00
else do not change hours
.如果 'AM' 和hours == 12
然后 hours 设置为00
否则不会改变hours
。
If 'PM' and hours == 12
then do not change hours
else hours is set to hours = hours+12
.如果 'PM' 和hours == 12
则不要更改hours
否则 hours 设置为hours = hours+12
。
Do use SimpleDateFormat
:使用SimpleDateFormat
:
public static String to24Time(String str) throws ParseException {
DateFormat df12 = new SimpleDateFormat("hh:mm:ssa", Locale.US);
DateFormat df24 = new SimpleDateFormat("HH:mm:ss", Locale.US);
return df24.format(df12.parse(str));
}
PS This is task from Hackerrank: Algorithms/Warmup/Time Conversion . PS这是来自 Hackerrank: Algorithms/ Warmup /Time Conversion 的任务。
PPS In case you do not want to use SimpleDateTime
, this is example how to use Regular Expression . PPS如果您不想使用SimpleDateTime
,这是如何使用正则表达式的示例。 Note, that I do not provide full validation of input sting;请注意,我不提供输入字符串的完整验证; in some cases (eg for illegal 12h time format like 21:17:17PM) it returns illega result instead of exception:在某些情况下(例如对于非法的 12 小时时间格式,如 21:17:17PM),它返回 illega 结果而不是异常:
public static String to24Time(String str) throws ParseException {
final Pattern TIME_12 = Pattern.compile("(?<hour>\\d{2}):(?<minute>\\d{2}):(?<second>\\d{2})(?<part>am|pm)");
Matcher matcher = TIME_12.matcher(str.toLowerCase());
if (matcher.matches()) {
int hour = Integer.parseInt(matcher.group("hour"));
return ("pm".equals(matcher.group("part")) ? hour + 12 : hour) + ":" + matcher.group("minute") + ':' + matcher.group("second");
}
return null;
}
Here is how I solved it using JavaScript:这是我使用 JavaScript 解决它的方法:
function timeConversion(s) {
var res;
var pos = s.substring(-2, 8);
var split = pos.split(':');
if (split[0] == 12 && s.endsWith('AM')) {
res = '00' + ':' + split[1] + ':' + split[2];
} else if (split[0] == 12 && s.endsWith('PM')) {
res = '12' + ':' + split[1] + ':' + split[2];
} else if (split[0] < 12 && s.endsWith('AM')) {
res = split[0] + ':' + split[1] + ':' + split[2];
} else if (split[0] < 12 && s.endsWith('PM')) {
var add = Number(split[0]) + 12;
res = add + ':' + split[1] + ':' + split[2];
}
return res;
}
static String timeConversion(String s) {
int hrs = 12;
String[] split = s.split(":");
String originalAMPM = split[2].substring(2,4);
String hours = split[0]; String minutes = split[1]; String seconds = split[2].substring(0,2);
if(originalAMPM.equals("PM")) {
if(!hours.equals("12"))
hrs = Integer.parseInt(hours) + 12;
return hrs + ":" + minutes + ":" + seconds;
}
else {
if(hours.equals("12"))
hours = "00";
return hours + ":" + minutes + ":" + seconds;
}
}
#!/bin/python3
import os
import sys
import re
#
# Complete the timeConversion function below.
def timeConversion(s):
if s[len(s)-2:]=='PM':
if s[0] == '0':
s1=s.strip('0')
sn = s1.strip('PM')
return sn.replace(sn[0],str(int(sn[0])+12))
elif s[0:2]=='12':
return s.strip('PM')
else:
sn = s.strip('PM')
return sn.replace(sn[0:2],str(int(sn[0:2])+12))
else: #s[len(s)-2:]=='AM':
if s[0:2]=='12':
s1=s.strip('AM')
return s1.replace(s[0:2],'00')
else:
return s.strip('AM')
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
s = input()
result = timeConversion(s)
f.write(result + '\n')
f.close()
Here is how I solved it using JavaScript:这是我使用 JavaScript 解决它的方法:
function timeConversion(s) {
let time = [];
let mid = s.slice(0,2);
if(s.includes('PM')){
if( mid === '12' ){
time = s;
} else{
let mid1 = Number(mid)+12;
time = s.replace(mid, mid1.toString());
}
} else if(mid === '12'){
time = s.replace(mid, '00');
} else time = s;
return time.slice(0,-2);
};
SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss aa");
StringBuilder std = new StringBuilder(s);
if(std.toString().contains("P"))
{
std.insert(std.indexOf("P"), " ");
}else{
std.insert(std.indexOf("A"), " ");
}
String.format("%tT",df.parse(std.toString())));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.