noaman_wgs

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

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

 1 package com.exe10.offer;
 2 
 3 /**
 4  * 【题目】求1+2+3+…+n,
 5  *             要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
 6  * @author WGS
 7  *
 8  */
 9 public class SumOfN {
10     int result=0;
11     
12     public boolean calc(int n){
13         result+=n;
14         return n!=0 && calc(n-1);//只要n!=0  就一直递归执行加运算.
15     }
16     
17     public int getSum(int n){
18         if(n<0) return -1;
19         calc(n);//只要calc函数中n==0 就为false 跳出calc函数,执行下步的return result
20         return result;
21     }
22     public static void main(String[] args) {
23         SumOfN s=new SumOfN();
24         int n=s.getSum(-10);
25         System.out.println(n);
26 
27     }
28 
29 }

 

posted on 2016-06-25 11:09  noaman_wgs  阅读(122)  评论(0)    收藏  举报