Java > Recursion-1 > bunnyEars2 (CodingBat Solution)

Problem:

We have bunnies standing in a line, numbered 1, 2, ... The odd bunnies (1, 3, ..) 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 number of "ears" in the bunny line 1, 2, ... n (without loops or multiplication).

bunnyEars2(0) → 0
bunnyEars2(1) → 2
bunnyEars2(2) → 5


Solution:

public int bunnyEars2(int bunnies) {
  if (bunnies == 0) return 0;
  if (bunnies % 2 == 0) return 3 + bunnyEars2(bunnies-1);
  else return 2 + bunnyEars2(bunnies-1);
}


13 comments :

  1. public int bunnyEars2(int bunnies) {
       if(bunnies==0)return 0;
       return bunnyEars2(bunnies-1)+3-bunnies%2;
    }

    ReplyDelete
  2. public int bunnyEars2(int bunnies) {
    return bunnies*5/2;
    }

    ReplyDelete
    Replies
    1. You have to do it without loops or multiplication.

      Delete
  3. public int bunnyEars2(int bunnies) {
    if(bunnies==0)return 0;
    if(bunnies==1)return 2;
    if(bunnies==2)return 5;
    return 5+bunnyEars2(bunnies-2);
    }

    ReplyDelete
  4. public int bunnyEars2(int bunnies) {
    if (bunnies == 0) return 0;
    if (bunnies % 2 == 0)
    return 3 + bunnyEars2(bunnies-1);
    else return 2 + bunnyEars2(bunnies-1);
    }
    question:
    1 bunny = 2 ears; if bunnies %2 == 0 - yes, so add 3
    2 bunny = 5 ears; if bunnies %2 == 0 - no, so add 2
    3 bunny = 7 ears; if bunnies %2 == 0 - no 7%2 is 1, why does it
    add 3 instead 2?

    ReplyDelete
  5. return (bunnies ==0)? 0 : 2 + (bunnies-1)%2 + bunnyEars2(bunnies-1);

    ReplyDelete
  6. public int bunnyEars2(int bunnies) {
    if(bunnies == 0) {
    return 0;
    }
    if(bunnies % 2 == 1) {
    return 2 + bunnyEars2(bunnies - 1);
    } else {
    return 3 + bunnyEars2(bunnies - 1);
    }
    }

    ReplyDelete
  7. Replies
    1. no, because the challenge states, "(without loops or multiplication)."

      It may be completed easily with loops, but that is not the point.

      Delete
  8. public int bunnyEars2(int bunnies) {
    if (bunnies == 0) return 0;
    if (bunnies == 1) return 2;
    return 5 + bunnyEars2(bunnies - 2);
    }

    ReplyDelete
    Replies
    1. The idea here is simple, every 2 bunnies is 5 ears. Lines 2 and 3 remove the need for a %2 all together.

      hope that helps.

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

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact