jn1kk
jn1kk

Reputation: 5102

Calculate Hour Difference Between Two Times In a Day(s)

Just wanted to know if this function's results will always hold?

private int calcHourDiff(int start, int end) {

    int diff;

    if(start > end) {
        diff = ((2400 - start) + end) / 100;
    } else if(start < end) {
        diff = (end - start) / 100;
    } else {
        diff = 0;
    }

    return diff;

}

Functions are passed in as military time and it should return the amount of hours in between. Passed in values will always be "easy" numbers such as 1200, 1400, 2100 not 2134 or 015. It needs to be able to properly calculate all possible cases, will this function hold?

I had trouble for values ranging from the night (8PM or 2000) to the next day (6AM or 600) and I think this should fix it?

Thanks for the time.

Upvotes: 0

Views: 1133

Answers (3)

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

Just to be different, here's a version without any conditionals at all:

private int calcHourDiff(int start, int end) {
    return ((end - start + 2400) % 2400) / 100;
}

Upvotes: 2

John B
John B

Reputation: 32949

private int calcHourDiff(int start, int end) {

  int newEnd = (start > end)?end + 2400 : end;
  return (newEnd - start) / 100;
}

Upvotes: 0

CLo
CLo

Reputation: 3730

Looks good.

When comparing two numbers, x and y, there are only 3 possible outcomes: x == y, x < y, x > y

Your if block covers all three, and the math for each condition looks good.

Just would be worried about the assumption that the data passed will always be "easy" and correct.

Upvotes: 0

Related Questions