面试题:求1+2+……+n
题目:求1+2+……+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)
参考:
https://blog.csdn.net/qq_43165002/article/details/89607472
https://blog.csdn.net/Lynn_Baby/article/details/79724299
方法:
一、使用逻辑运算符结束递归
利用“或者“逻辑运算符,前面为真,就不用计算后边的特点,使得n=0的时候就可以停止递归
利用”并且“逻辑运算符,前面为假,也不用计算后边的特点,使用n>0来停止递归。
左右都必须是关系运算符的表达式,目的是让后边的运行。
二、利用异常结束递归
当出现异常情况时,跳出递归
(对边界0、1可用,但对异常输入如负数,不可用)
代码:
public class Q64 {
public static void main(String[] args) {
int n = -1;
System.out.println(sum1(n));
}
// 用逻辑运算符结束递归
// 当n>0不成立时,&&不会再继续后面的操作
public static int sum(int n) {
int re = n;
boolean flag = (n>0) && (re = re +sum(n-1))>0;
return re;
}
// 用异常结束递归
// 当n为0时,停止
public static int sum1(int n) {
int re = n;
try {
int i=1/n;
re = re + sum1(n-1);
return re;
}catch (Exception e) {
return re;
}
}
}