-
EvenNumbersmyCode/ShortestCodeChallenge 2016. 7. 4. 13:19
https://codefights.com/challenge/4HANW3Rbjcs9TZmMM/main
2000Number
Xis called twice even if it is divisible by2, and numberX / 2is also divisible by2, yetX / 2 / 2is not. For example,X = 12is twice even, since12 / 2 = 6- even, and6 / 2 = 3is not even.You're given two numbers:
NandP. Find the largest numberX, such that1 ≤ X ≤ PandXis divisible by2exactlyNtimes. If there's no such number, return-1instead.Example
For
N = 2andP = 15, the output should beEvenNumbers(N, P) = 12.12 / 2 = 6and6 / 2 = 3, which is not even.Input/Output
- [time limit] 500ms (cpp)
[input] integer N
Constraints:
0 ≤ N ≤ 30.[input] integer P
Constraints:
1 ≤ P ≤ 2 · 109.[output] integer
The largest number
X, such that1 ≤ X ≤ PandXis divisible by2exactlyNtimes. If this number does not exist return-1instead.
* 이 문제에 주목하는 이유 *
문제 유형중에 이런 유형이 많다.
"어떤 정수 P가 주어졌을때, P보다 크지 않으면서 ~~~조건을 만족하는 최대의 정수를 찾아라."
당장 떠오르는 해결방법은 P에서 하나씩 값을 감소해나가면서 조건을 만족하는지 계속 검사하는 것인데
이 방법으로 풀면 시간 제한때문에 번번히 실패한다.
실제로 이 문제를 해결하기 위해 다음과 같이 코드를 짰지만 시간 제한 초과로 실패했다.
int EvenNumbers(int N, int P) {
int n = int(pow(2,N));
while (P>0) {
if(P%n ==0 && (P/n)%2 != 0) return P;
P--;
}
return -1;
}
그럼 어떤 식으로 해야하는걸까?
예제 답안1)
int EvenNumbers(int N, int P) {
int t = pow(2,N);
for(int i=P/t; i>=1; i--){
if(i%2!=0){
return i*t;
}
}
return -1;
}
조금의 수학적인 계산으로 for문의 범위를 확실하게 줄였다.
'myCode > ShortestCodeChallenge' 카테고리의 다른 글
pascal_list [reverse_challenge] (0) 2016.07.26 Fact (Reverse Challenge) (0) 2016.07.04 Reverse_t9 (0) 2016.06.08 Cipher_Zeroes [Decimal to Binary] (0) 2016.06.04 Turns on Road (0) 2016.05.17