Find the day of the week after K days from the given day
Last Updated :
29 Nov, 2023
Content has been removed on Author’s request.
Using Naive Approach:
Approach:
One approach to find the day of the week after K days from a given day is to use a brute-force method where we add K days to the given day and then find the corresponding day of the week.
Algorithm:
Input the day and K
Add K days to the given day
Find the corresponding day of the week using the modulus operator (%)
Return the day of the week
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<string> daysOfWeek = { "Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" };
string day = "Monday" ;
int K = 100;
int index = find(daysOfWeek.begin(), daysOfWeek.end(), day) - daysOfWeek.begin();
int newDay = (index + K) % 7;
cout << daysOfWeek[newDay] << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> daysOfWeek = Arrays.asList( "Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" );
String day = "Monday" ;
int K = 100 ;
int newDay = (daysOfWeek.indexOf(day) + K) % 7 ;
System.out.println(daysOfWeek.get(newDay));
}
}
|
Python3
days_of_week = [ "Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" ]
day = "Monday"
K = 100
new_day = (days_of_week.index(day) + K) % 7
print (days_of_week[new_day])
|
C#
using System;
using System.Collections.Generic;
class Program {
static void Main()
{
List< string > daysOfWeek = new List< string >{
"Sunday" , "Monday" , "Tuesday" , "Wednesday" ,
"Thursday" , "Friday" , "Saturday"
};
string day = "Monday" ;
int K = 100;
int index = daysOfWeek.IndexOf(day);
int newDay = (index + K) % 7;
Console.WriteLine(daysOfWeek[newDay]);
}
}
|
Javascript
const daysOfWeek = [ "Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" ];
const day = "Monday" ;
const K = 100;
const index = daysOfWeek.indexOf(day);
const newDayIndex = (index + K) % 7;
const newDay = daysOfWeek[newDayIndex];
console.log(newDay);
|
This approach requires O(K) time complexity
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...