【微软100题】求1+2+…+n

来源:互联网 发布:mac系统迁移到ssd 编辑:程序博客网 时间:2024/05/29 04:32
题目:求1+2+…+n,

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

package test;/** * 题目:求1+2+...+n,要求不能使用乘除法,for,while,if,else,switch,case,条件判断语句(A?B:C) * @author Zealot * *思路,定义数组,设置大小,试用try,catch跳出递归。 *递归终止条件:数组越界,捕获异常 */public class Sum {private static int sum =0;private static int[] array = new int[100];private static int n = 0;private void add() {n++;try{array[n-1] =n;sum+=n;add();} catch(Exception e) {System.out.println("终止");}}public static void main(String[] args) {Sum s = new Sum();s.add();System.out.println(sum);}}


0 0