1. 程式人生 > >java題目:求 1+2+...+n,要求不能用除法、 for、 while、 if、 else、 switch、 case 等關鍵字及條件判斷語句( A?B:C)。

java題目:求 1+2+...+n,要求不能用除法、 for、 while、 if、 else、 switch、 case 等關鍵字及條件判斷語句( A?B:C)。

這是劍指offer的46道面試題,由於面試官諸多條件的限制,本文采用遞迴的手法完成程式碼

public class Sum {
    public static void main(String[] args) {

        System.out.println(sum(1));
    }
    static int sum(int n){
           return n>0 ? n + sum(n-1) : 0 ;

    }
}

執行結果如圖所示
這裡寫圖片描述