【剑指offer-Java版】46求 1 + 2 + 3 + ... + n

求 1 + 2 + … + n 但是不能使用判断,循环,分支,条件判断语句以及乘除运算

利用反射实现递归:目标就是构建一个递归出口


    public class _Q46<T> {

    public int terminator(int n){
        return 0;
    }

    public int sum(int n) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
        List<Boolean> list = new ArrayList<>();
        list.add(false);
        list.add(true);
        // reflecting all the public member methods of the class or interface represented by this Class object
        // The elements in the array returned are not sorted and are not in any particular order.
        Method methods[] = this.getClass().getMethods();
        int index = list.indexOf(n == 0); // 仅当n==0的时候执行terminator()方法
        return n + (int)methods[index].invoke(this, (--n));
    }
    }

测试代码:

    public class _Q46Test extends TestCase {

    _Q46<?> sum = new _Q46();

    public void test() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{

        System.out.println(sum.sum(100));
    }
    }

你可能感兴趣的:(【剑指offer-Java版】46求 1 + 2 + 3 + ... + n)