在不使用乘除,for, while等循环关键字以及if,else,switch,三目运算等条件语句的情况下如何计算1+2+3+4+5+6+…+n。
public class TestMatch {
@Test
public void test() {
int n = 75;
System.out.println(sum(n));
System.out.println(sumWithFor(n));
System.out.println(sumWithStream(n));
}
public int sum(int n) {
int sum = n;
boolean flag = n > 0 && (sum += sum(n -1)) > 0;
return sum;
}
/**
* for循环验证sum()运算结果
* @param n
* @return
*/
public int sumWithFor(int n) {
int sum = 0;
if(n <= 0) {
return sum;
}
for(int i = 0; i <= n; i++) {
sum += i;
}
return sum;
}
public int sumWithStream(int n) {
return IntStream.rangeClosed(1, n).sum();
}
}
}
递归求和无循环

本文介绍了一种在不使用循环和条件语句的情况下计算从1到n的累加和的方法,通过递归函数实现。同时,提供了使用for循环和Java 8 Stream API的对比实现。
1517

被折叠的 条评论
为什么被折叠?



