Read a number of seconds (possibly very large) and print it as days, hours, minutes and seconds, using long arithmetic and / and %.
Solution
Main.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLong()) {
long total = in.nextLong();
long days = total / 86_400;
long hours = total % 86_400 / 3_600;
long minutes = total % 3_600 / 60;
long seconds = total % 60;
System.out.printf("%,d s = %dd %02dh %02dm %02ds%n", total, days, hours, minutes, seconds);
}
}
}
Output Verified by compiling and running
59 s = 0d 00h 00m 59s
3,725 s = 0d 01h 02m 05s
100,000 s = 1d 03h 46m 40s
3,000,000,000 s = 34722d 05h 20m 00s
3 billion does not fit in an int, so long is used throughout. % 86_400 / 3_600 extracts the hours within a day.
More Java Basics, Syntax and Data Types practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!