public static init sumDigits(int i) {
return i == 0 ? 0 : i % 10 + sumDigits(i / 10);
}
explanation: First of all correct the return type of the method which is written init
instead of int
.
actually the return statement says that,
if the value of i
is 0
then return 0
else return i % 10 + sumDigits(i / 10)
here ?
determines whether the condition (i==0)
is true or false. If the condition satisfies(i.e true) then simply return 0 else do some operation with the value of i
It could have been written as below:
public static int sumDigits(int i) {
if(i==0)
return 0;
else
return i % 10 + sumDigits(i / 10);
} // that will result the same as above but with less amount of code.