求 1+2+…+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
看到累加想到使用递归,但是不能用关键字,递归需要出口,使用逻辑运算符来实现出口。
&&运算符
A&&B,如果A返回false,A&&B为false,表达式执行A。
||运算符
A||B,如果A返回true,A||B为true,表达式执行A。
public class Solution {
public int result;
public int SumNums(int n)
{
he(n);
return result;
}
public bool he(int n)
{
result += n;
return n == 0 || he(n - 1);//true返回n==0跳出,反之递归。
}
}