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++
// Nikunj Sonigara #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
// Nikunj Sonigara 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 of days of the week
List< string > daysOfWeek = new List< string >{
"Sunday" , "Monday" , "Tuesday" , "Wednesday" ,
"Thursday" , "Friday" , "Saturday"
};
// Initial day and number of days to add
string day = "Monday" ;
int K = 100;
// Find the index of the initial day in the list
int index = daysOfWeek.IndexOf(day);
// Calculate the new day index after adding K days,
// considering the circular nature of days
int newDay = (index + K) % 7;
// Output the resulting day
Console.WriteLine(daysOfWeek[newDay]);
}
} |
Javascript
// Define an array with the days of the week const daysOfWeek = [ "Sunday" , "Monday" , "Tuesday" , "Wednesday" , "Thursday" , "Friday" , "Saturday" ];
// Define the starting day const day = "Monday" ;
// Define the number of days to add const K = 100; // Find the index of the starting day in the array const index = daysOfWeek.indexOf(day); // Calculate the new day index by adding K and taking the modulo 7 const newDayIndex = (index + K) % 7; // Find the new day of the week in the array const newDay = daysOfWeek[newDayIndex]; // Print the new day of the week console.log(newDay); |
Output
Wednesday
This approach requires O(K) time complexity
Auxiliary Space: O(1)
Recommended Articles