Re: Int->String formatting method
Oliver Wong wrote:
"Deniz Dogan" <kristnjov@nospam.com> wrote in message
news:efanv0$l2m$1@gide.ita.chalmers.se...
Deniz Dogan wrote:
Hello again! Yes, I have yet another problem for all of you great
programmers in here.
This should actually be a pretty easy task to complete, but somehow
the blood in my veins doesn't seem to flow the right way just now.
Here's the problem:
I have an amount of milliseconds, in the range [0,Integer.MAX_VALUE]
and I want to format it to a String of the format "HH:nn:ss,mmm"
where HH ranges between 00-99, nn between 00-59, ss between 00-59 and
mmm between 000-999 (all of the ranges inclusive).
The only thing I can come up with now as a solution is a bunch of
if-then-else statements, but really now, we shouldn't have to go and
do that, do we?
I love stating problems. Looking forward to your help.
/Deniz Dogan
Disregard my post, a friend of mine solved it on four rows of code and
O(1) fashion.
You should have post the solution, in case someone in the future
stumbles upon this post via google and has a similar problem and is
looking for the solution.
here's my guess at the solution:
public static String toTimeString(long milliseconds) {
final long MS_PER_SEC = 1000;
final long MS_PER_MIN = MS_PER_SEC * 60;
final long MS_PER_HOUR = MS_PER_MIN * 60;
final long hours = milliseconds / MS_PER_HOUR;
milliseconds %= MS_PER_HOUR;
final long minutes = milliseconds / MS_PER_MIN;
milliseconds %= MS_PER_MIN;
final long seconds = milliseconds / MS_PER_SEC;
milliseconds %= MS_PER_SEC;
StringBuffer sb = new StringBuffer();
sb.append(hours);
sb.append(":");
sb.append(minutes);
sb.append(":");
sb.append(seconds);
sb.append(",");
sb.append(milliseconds);
return sb.toString();
}
- Oliver
And here's my friend's solution:
public static String formatMillis(int millis) {
int ihh = millis/3600000; //amount of hours
int inn = (millis - ihh*3600000) / 60000; //amount of minutes
int iss = (millis - (ihh*3600000) - (inn * 60000)) / 1000; //amount
of seconds
int immm = (millis - (ihh*3600000) - (inn * 60000)) - iss*1000;
//amount of milliseconds
//String representations of the integers:
String mmm = "" + immm, ss = "" + iss, nn = "" + inn, hh = "" + ihh;
//Making sure the lengths of the Strings are correct:
if (mmm.length() == 1) mmm = "00" + mmm;
else if (mmm.length() == 2) mmm = "0" + mmm;
if (ss.length() == 1) ss = "0" + ss;
if (nn.length() == 1) nn = "0" + nn;
if (hh.length() == 1) hh = "0" + hh;
return hh + ":" + nn + ":" + ss + "," + mmm;
}
I have a question for you Oliver (or anyone else who'd want to answer
this question), is your solution faster than mine? I considered using
the modulo operator, but I wasn't sure how the JVM would implement it. I
figured it would just do a lot of division operations until it couldn't
divide it any more, but perhaps it implements it in a different manner?
- Deniz Dogan