Recursion - 1 (bunnyEars2) Java Solution || Codingbat.com

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

We always add at least 2 ears, but when bunnies is even, we add one more. So we always add 2 + ((bunnies+1) % 2), since odd % 2 = 1, and even % 2 = 0. So all you have to do is:

if (bunnies == 0) return 0;
else return bunnyEars2(bunnies-1) + 2 + ((bunnies+1) % 2);

trumbaron
Автор

i'm write that code like that:
int ears = 0;
public int bunnyEars2(int bunnies) {
if(bunnies != 0){
if(bunnies%2 == 0){
ears = ears + 3;
}
else{
ears = ears + 2;
}
bunnyEars2(bunnies-1);
}
return ears;
}
but that's don't work in that compiler, otherwise work in intelij, what's the problem?

animvees
Автор

I believe i have the simplest solution

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

amichaeel
welcome to shbcf.ru