gpt4 book ai didi

java - Hackerrank 上的时间转换挑战返回空小时

转载 作者:太空宇宙 更新时间:2023-11-04 13:04:24 24 4
gpt4 key购买 nike

我正在尝试Time Conversion Hackerrank 上的挑战,但由于某种原因,24 小时表示中的小时字段总是显示为空。这是挑战 -

Problem Statement

Given a time in AM/PM format, convert it to military (24-hour) time.

Note: Midnight is 12:00:00AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00PM on a 12-hour clock and 12:00:00 on a 24-hour clock.

另一个问题似乎是秒总是显示为 1 位数。例如,如果输入为 07:05:45PM,我的 Hackerrank 输出为 :05:4

但是,代码在我的桌面上的 IntelliJ 中运行得很好 -

1:24:23AM
1
24
23AM
01:24:23

Process finished with exit code 0

07:05:45PM
07
05
45PM
19:05:45

Process finished with exit code 0

由于无法在 hackerrank 本身上调试解决方案,因此我不确定出了什么问题。这是我的代码 -

package algorithms.Warmup;

import java.util.Scanner;

/**
* Created by manishgiri on 1/6/16.
*/
public class TimeConversion {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String time = in.next();
String[] parts = time.split(":");
for(String part: parts){
System.out.println(part);
}
int hours = Integer.parseInt(parts[0]);
String minutes = (parts[1]);
String[] last = parts[2].split("");

String seconds = last[0]+last[1];
String timeZ = last[2]+last[3];
String finalHour = "";
if(timeZ.equalsIgnoreCase("PM")) {
if(hours == 12) {
finalHour = Integer.toString(12);
}
else {
finalHour = Integer.toString(hours + 12);
}
}
else if(timeZ.equalsIgnoreCase("AM")) {
if(hours == 12) {
finalHour = "00";
}
else if(hours == 10 || hours == 11) {
finalHour = Integer.toString(hours);
}
else {
finalHour = "0"+hours;
}
}
System.out.println(finalHour+":"+minutes+":"+seconds);


}
}

最佳答案

尝试下面的代码。希望评论有助于理解逻辑。

static String timeConversion(String s) {
// Split the string by :
String[] sTime = s.split(":");

int x = 0;

// if PM and hours >12, add additional 12 to hours
// for AM and hour = 12, set hour to 00
if(sTime[sTime.length - 1].contains("PM") && !sTime[0].equals("12"))
x = 12;

String val1 = "";
if(x == 12)
val1 = (Integer.parseInt(sTime[0]) + x) + "";
else {
if(sTime[0].equals("12") && sTime[sTime.length - 1].contains("AM"))
val1 = "00";
else
val1 = sTime[0];
}

// merge the string and return the result
String result = val1 + ":" + sTime[1] + ":" + sTime[2].substring(0,2);
return result;
}

干杯!

关于java - Hackerrank 上的时间转换挑战返回空小时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34631339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com