Development/CodeWorkout

[CodeWorkout] X158: bunnyEars2

bbubbush 2022. 5. 5. 00:10

 

Question

We have bunnies standing in a line, numbered 1, 2, ... The odd bunnies (1, 3, 5, ...) have the normal 2 ears. The even bunnies (2, 4, ...) we'll say have 3 ears, because they each have a raised foot. Recursively return the total number of "ears" in the bunny line 1, 2, ... n (without using loops or multiplication).

 

Answer

반응형
package com.bbubbush.tistory;

public class X158 {
  public static void main(String[] args) {
    int bunnies;
    bunnies = 3;
    System.out.printf("[bunnies = %d]\n", bunnies);
    System.out.println(bunnyEars2(bunnies));
    bunnies = 5;
    System.out.printf("[bunnies = %d]\n", bunnies);
    System.out.println(bunnyEars2(bunnies));
    bunnies = 9;
    System.out.printf("[bunnies = %d]\n", bunnies);
    System.out.println(bunnyEars2(bunnies));
  }

  public static int bunnyEars2(int bunnies) {
    if (bunnies == 0) {
      return 0;
    }
    return (bunnies % 2 != 0 ? 2 : 3) + bunnyEars2(bunnies - 1);
  }
}

 

Ref

https://github.com/bbubbush/codeworkout/blob/master/src/com/bbubbush/tistory/X158.java

 

GitHub - bbubbush/codeworkout

Contribute to bbubbush/codeworkout development by creating an account on GitHub.

github.com

 

'Development > CodeWorkout' 카테고리의 다른 글

[CodeWorkout] X323: sumRange  (0) 2022.05.06
[CodeWorkout] X119: squareUp  (0) 2022.04.27
[CodeWorkout] X121: extraEnd  (0) 2022.04.26
[CodeWorkout] X125: repeatSeparator  (0) 2022.04.25