"0719 Even Odd Query"의 두 판 사이의 차이

ph
이동: 둘러보기, 검색
(새 문서: [https://www.hackerrank.com/challenges/even-odd-query/problem 문제 링크] 아래와 같이 배열이 주어지면(semi-positive) 그중에 임의의 구간을 준다. 그러면...)
 
잔글
1번째 줄: 1번째 줄:
 
[https://www.hackerrank.com/challenges/even-odd-query/problem 문제 링크]
 
[https://www.hackerrank.com/challenges/even-odd-query/problem 문제 링크]
  
아래와 같이 배열이 주어지면(semi-positive) 그중에 임의의 구간을 준다. 그러면 아래 보는 그림과 같이 pow의 중첩값을 구해서 그것의 홀짝을 맞추는 문제.
+
아래와 같이 (semi-positive)배열이 주어지면 그중에 임의의 구간을 준다. 그러면 아래 보는 그림과 같이 pow의 중첩값을 구해서 그것의 홀짝을 맞추는 문제.
 
$$ [ \dots , 2 , 0, 2, 4, \underbrace{6, 4, 3, 7}_{\large{6^{4^{3^7}}}}, 1, 2, 4, 7, 0, 9, 8, 4, \dots ] $$
 
$$ [ \dots , 2 , 0, 2, 4, \underbrace{6, 4, 3, 7}_{\large{6^{4^{3^7}}}}, 1, 2, 4, 7, 0, 9, 8, 4, \dots ] $$
  

2017년 7월 20일 (목) 00:11 판

문제 링크

아래와 같이 (semi-positive)배열이 주어지면 그중에 임의의 구간을 준다. 그러면 아래 보는 그림과 같이 pow의 중첩값을 구해서 그것의 홀짝을 맞추는 문제. $$ [ \dots , 2 , 0, 2, 4, \underbrace{6, 4, 3, 7}_{\large{6^{4^{3^7}}}}, 1, 2, 4, 7, 0, 9, 8, 4, \dots ] $$

늘 그렇듯 이런문제도 값을 실제로 구할 필요는 없고 홀짝만 구하면 된다. 문제에 보면 아래 함수의 리턴값을 구하는 것이라고 되어 있는데 위 그림에서 설명한 것과 같다.(아래에서 x, y가 위의 그림에서 시작과 끝 index다.)

find(int x,int y)
{
    if(x>y) return 1;
    ans = pow(A[x],find(x+1,y))
    return ans
}

어찌어찌해서 여러 경우를 나누는 방법으로 해결하기는 했는데, 뭐 이것도 늘 그렇듯이 모법답안이 훨씬 더 간결하다. 설명은 다음과 같고,

There are 3 conditions that needs to be checked in the following order.

  1. If A[a] is odd, irrespective of what A[b] is, the answer is odd.
  2. If a == b, then the answer is even ( as the condition #1 is executed in case the number is odd).
  3. If A[a+1] == 0, then the answer is odd as x0 = 1.

If none of the above conditions match, return even.

코드도 간결하다. 아래가 핵심부분

int find(int x, int y){
    if(A[x]%2) return 1;
    if(x == y) return 0;
    if(A[x+1] == 0) return 1;
    return 0;
}

저 세 조건의 순서를 바꾸면 처리하기가 훨씬 더 복잡해진다. 내가 그렇게 했다고...

find함수를 아래와 같이 하면 훨씬 더 보기 좋은것 같은데,

def find(x,y):
    if x>y:
        return 1

    v = find(x+1, y)
    if v == 0:
        return 1

    return a[x] # Isn't this cool?

실제로 해보면,

RuntimeError: maximum recursion depth exceeded

ㅇㅇ


blog comments powered by Disqus