+ 2

Code problem

public static String ben (int x){ if (x /5 <=0) return x %5; else return (x % 5) + ben (x/5); } When I pass 51 into ben() what will be the output? Can anyone please explain. Options are 202 201 102 101

21st Oct 2020, 9:07 PM
SG713
SG713 - avatar
3 Antworten
+ 4
Well first you have to fix the ben() method so that it actually returns String or change the return type. So, I'll answer as if the return type is String since that is what is needed to get the answer from the available choices. The if statements condition will be false. This is integer division so the fractional part will be truncated. 51/5 = 10 not 10.2 in this case So the else statement is ran. x % 5 = 1 Using the modulo operator % will return the remainder from division. 51 / 5 has a remainder of 1. That is 5 goes into 51, 10 times leaving 1 left over. 10 * 5 = 50 51 - 50 = 1 So, "1" + ben(51/5) is returned The recursive call to ben that is returned is equivalent to ben(10) due to integer division The if statement is false 10/5 = 2 So, here (10 % 5) + ben(10/5) is returned Which is "0" + ben(2) now we have "1" + "0" + ben(2) The if statement is true due to integer division. 2/5 = 0 Returns 2 % 5 = 2 2 divided by 5 is 0 with a remainder of 2 "1" + "0" + "2" "102"
21st Oct 2020, 10:28 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
In your code sample, it return type is string, so you are forgetting to form string in return statement.. So it is error. It shloud be return ""+(x%5); now this return converted string. In next return also should change like this. If it return string, if you pass 51 then In if 51/5<=0 => 10<=0 false then it return "" +(51%5) +ben(51/5) => 1+ben(10) Next ben(10)=> 10/5<=0 false so it return 10%5 +ben(10/5) => 0+ben(2) Next ben(2)=> 2%5<=0 is true so it return ""+(2%5) =>2 So finally "" +1+(0+ (2)) "102" a string form. In your code if you change return type to int, then answer is 1+0+2=3
21st Oct 2020, 10:22 PM
Jayakrishna 🇮🇳
+ 1
with correction return String.valueOf(x % 5); x=51 if 51/5 = 10; 10 <= 0 false else return 51 % 5 = 1 + x= 51/5 = 10 if 10/5 = 2; 2 <= 0 false else return 10 % 5 = 0 + x= 10/5 = 2 if 2/5 = 0; 0 <= 0 true return 2 % 5 = 2 String 1+"0"+"2"
21st Oct 2020, 10:39 PM
zemiak