《剑指offer》数学第二题:求1+2+3+...+n

题目描述:

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

思路:

       我们可以用递归和短路运算符来进行运算,具体代码如下。

代码实现:

package 数学;
import java.util.Scanner;

public class Math2 {

    public int solution(int n)
    {

        if(n==0)
            return 0;
        int s=n;
        boolean sign=((n>0)&&(s+=solution(n-1))>0)  ;
        return s;

    }

    public static void main(String[] args) {
        Math2 m=new Math2();
        Scanner sc=new Scanner(System.in);

        int n=sc.nextInt();
        System.out.println(m.solution(n));
    }
}

 测试结果:

《剑指offer》数学第二题:求1+2+3+...+n_第1张图片

你可能感兴趣的:(算法)