Q 2948 2009๋
๐ก ๋ฌธ์ ์์ฝ ๋ฐ ๋ถ์
2009๋ ๋ ์ง๊ฐ ์ฃผ์ด์ก์ ๋, ๋ฌด์จ ์์ผ์ธ์ง ์ถ๋ ฅํ์. ์ฐธ๊ณ ๋ก, 2009๋ 1์ 1์ผ์ ๋ชฉ์์ผ์ด๋ฉฐ, ์ค๋ฌ์ ์๋ค.
๐ก ์๊ณ ๋ฆฌ์ฆ ์ค๊ณ
๋ฐฐ์ด์ ๋ ๊ฐ ์ ์ธํ๋ค.
int[] months = {0, 31, 28, 31, 30, ..., 31};String[] weeks = {"Thursday", "Friday", ..., "Wednesday"};M๊น์ง months ๋ฐฐ์ด์ ์ผ์๋ฅผ ๋ํ๊ณ , D ๋ฅผ ๋ํ๋ค.
for(int i = 0; i < M; i++) { ์ฐ์ฐ }๋ํ ๊ฐ์ 7๋ก ๋๋๊ณ , ๊ทธ ๋๋จธ์ง๊ฐ n ์ด๋ผ๋ฉด, weeks ๋ฐฐ์ด์์ n-1๋ฒ์งธ ์์๋ฅผ ์ถ๋ ฅํ๋ค.
๐ก ์ฝ๋
public class Main {
public static void main(String[] args) throws Exception {
int[] months = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String[] weeks = {"Thursday", "Friday", "Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"};
int D = read();
int M = read();
int count = 0;
for (int i = 0; i < M; i++) {
count += months[i];
}
count += D;
int n = count % 7 - 1;
// ArrayIndexOutOFBounds ์ ๋ํ ์์ธ ์ฒ๋ฆฌ
if (n == -1) {
System.out.println("Wednesday");
return;
}
System.out.println(weeks[n]);
}
static int read() throws Exception {
int c = 0, n = 0;
while ((c = System.in.read()) > 47) n = (n << 3) + (n << 1) + (c & 15);
return n;
}
}

๐ก ํ๋ฆฐ ๋ถ๋ถ ๋ถ์
์์ ๊ฐ์ ๋ฐฉ์์ด๋ผ๋ฉด โ์์์ผโ์ ๊ฒฝ์ฐ, n = -1 ์ด ๋์ด ๋ฒ๋ ค์ weeks[n] ์์ ๋ฐํ์ ์๋ฌ๊ฐ ๋ฐ์ํด์ ์ฝ๋๋ฅผ ์ด์ง ์์ ํ๋ค. ๋ค๋ง, ๊ฐ๋จํ ์ฐ์ฐ์ธ๋ฐ ์ฝ๋๊ฐ ๋๋ฌด ๊ธธ์ด์ ธ์ ์ข๋ ๋จ์ํ๊ฒ ์์ ํด ๋ณด์๋ค.
public class Main {
public static void main(String[] args) throws Exception {
int[] months = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
String[] weeks = {"Wednesday","Thursday","Friday","Saturday","Sunday","Monday","Tuesday"};
int D = read();
int M = read();
for (int i = 0; i < M; i++) {
D += months[i];
}
System.out.println(weeks[D%7]);
}
static int read() throws Exception {
int c = 0, n = 0;
while ((c = System.in.read()) > 47) n = (n << 3) + (n << 1) + (c & 15);
return n;
}
}
count ๋ณ์๋ฅผ ๊ตณ์ด ์ฌ์ฉํ ํ์๊ฐ ์์๋ค. ์ ๋ ฅ ๋ฐ์ ๋ ์ง D์ ์ด์ ๋ฌ์ ๋ ์ง๋ค์ ๋ํ๋ฉด ๋จ.
D % 7 - 1๋ก -1 ์ฐ์ฐ์ ํ ํ์ ์์ด, weeks ๋ฐฐ์ด ์์ฒด์์ ์์๋ฅผ ์กฐ์ ํ๋ฉด ๋๋ค. 1์ 1์ผ์ด ๋ชฉ์์ผ์ด์๊ธฐ ๋๋ฌธ์ ์ฒซ ์์๋ฅผ โThursdayโ ๋ก ์์ํ์ง๋ง, ์์ฒด์ ์ผ๋ก -1 ํ์ฌ โWednesdayโ ๋ฅผ ์ฒซ ์์๋ก ๋ง๋ค๋ฉด ๋ณต์กํ ์ฐ์ฐ์ด ํ์ ์๋ค.
๐ก ์๊ฐ ๋ณต์ก๋, ๊ณต๊ฐ ๋ณต์ก๋
| ์๊ฐ ๋ณต์ก๋ | ๊ณต๊ฐ ๋ณต์ก๋ |
|---|---|
| O(1) | O(1) |