逻辑运算符的短路特性 求1+2+3+...+n

来源:互联网 发布:ipad电视直播软件 编辑:程序博客网 时间:2024/04/29 00:42

题目描述

求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。

逻辑与的短路特性:当&&左部分的表达式为false,则不执行右部分的表达式

public class Solution {    public int Sum_Solution(int n) {    int sum = n;        boolean flag = (sum > 0) && ((sum += Sum_Solution(n - 1)) > 0);        return sum;    }}


逻辑或的短路特性:当||左部分的表达式为true,则不执行右部分的表达式
public class Solution {    public int Sum_Solution(int n) {        int sum = n;    boolean flag = (n == 0) || ((sum += Sum_Solution(n - 1)) > 0);        return sum;    }}


0 0