ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 4.12 재귀 템플릿 작성중
    코드스테이츠 2023. 4. 12. 23:42

    2 isOdd

     function isOdd(num) {
      if (num === 0) {	// base case: 0일때 (짝수)
        return false;	// false 리턴
      } else if (num === 1) {// base case: 1일때 (홀수)
        return true;		 // true 리턴
      }
    
      if (num < 0) {		// 만약 num이 음수인 경우엔
        return isOdd(-num);	// num에 (-)를 붙이고 isOdd 함수를 작동시켜 반환 (양수로 만듦)
      }
      return isOdd(num - 2);// 일반적인 경우 (양수), isOdd의 (num)자리에 (num-2)를 넣어 base case가 될때까지 계속 작동
    }

     

    05

    function arrSum(arr) {
      if (arr.length === 0) {// 빈 배열일 경우
        return 0;			// 0을 리턴한다.
      }
    
      // const [head, ...tail] = arr;
      const head = arr[0];			// arr 0번째 인덱스를 변수 head에 할당하고
      const tail = arr.slice(1);	// arr 0번째 인덱스를 제외한 나머지 부분을 변수 tail에 할당한다.
      return head + arrSum(tail);	// head + arrSum(tail) => basic case가 될 때까지 반복
    }

     

    14

    function unpackGiftbox(giftBox, wish) {
      // TODO: 여기에 코드를 작성합니다.
        if (giftBox.length === 0 || wish.length === 0) {
        return false;
      }
    
      for (let i = 0; i < giftBox.length; i++) {
        const element = giftBox[i];
        if (typeof element === 'string') {
          if (element === wish) {
            return true;
          }
        } else if (Array.isArray(element)) {
          if (unpackGiftbox(element, wish)) {
            return true;
          }
        }
      }
    
      return false;
    }

    '코드스테이츠' 카테고리의 다른 글

    4.13 UI 레이아웃  (0) 2023.04.14
    4.13 UI 디자인패턴  (0) 2023.04.13
    재귀  (1) 2023.04.11
    4.3 part1  (0) 2023.04.04
    3.11 개인복습  (0) 2023.03.11
Designed by Tistory.