Is it possible to add the numbers 1 to n recursively in Java with one return statement? How would you change the standard solution:
public static int sum(int n) {
if(n == 1) return n;
else return n + sum(n - 1);
}
return n == 1 ? n : n + sum(n-1);
You could use simple maths without recursion:
public static int sum(int n) {
return n * (n + 1) / 2;
}
Yes, by making use of the ternary operator :
public static int sum(int n) {
return n == 1 ? n : n + sum(n - 1);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With