Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java -- convert from number of weekdays to number of days

This is similar to Calculating dates given two dates excluding weekend but a different problem.

The question is "I was given a task N weekdays ago. How many days ago was this?"

On a Friday, 3 weekdays ago is 3 days ago. On a Monday, 3 weekdays ago is 5 days ago.

I can write a very simple solution by iterating. However, it strikes me that it should be possible to do this as an O(1) operation. A close but wrong answer is N + (7/5)N. Any tips?

like image 234
Jeremy Avatar asked Nov 01 '22 02:11

Jeremy


1 Answers

First convert even numbers of 5 days into 7 day weeks, then handle the remainder by adding two days if it will go over a weekend.

int MONDAY = 1, TUESDAY = 2, WEDNESDAY = 3, THURSDAY = 4, FRIDAY = 5;
int today = getToday();
int weeks = weekdays / 5;
int extraDays = weekdays % 5;
int days = weeks * 7;
if (today <= extraDays) {
    days += 2;
}
days += extraDays;
like image 125
Brigham Avatar answered Nov 15 '22 05:11

Brigham