编程题:求1+2+3+...+n

题目描述

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

思路:条件限制比较多,只能用递归了,fn=n+f(n-1)。

代码:

import java.util.Scanner;

/**
 * Created by ASUS on 2018/6/16
 *
 * @Authod Grey Wolf
 */
public class Practice {

    public static void main(String[] args) {

        Practice practice=new Practice();
        practice.sys();
    }

    private void sys() {
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt();
        int res=getSum(n);
        System.out.println(res);
    }

    private int getSum(int n) {
        int sum=n;
        //使用递归
        boolean flag=(n>0)&&((sum+=getSum(n-1))!=0);
        return sum;
    }


}

效果:

3
6

我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。


猜你喜欢

转载自blog.csdn.net/weixin_39220472/article/details/80714502