【劍指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));
    }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章