码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-09-27 22:31:54      阅读:263      评论:0      收藏:0      [点我收藏+]

标签:blog   turn   for   case   auto   返回   直接   bool   str   

解题思路:

这题采用递归算法,同时利用逻辑与&&的短路特性:前面的判断为true的话,才会执行后面语句中的递归。所以当n=0时,前面的判断为false,递归终止,直接返回0。

package bianchengti;
/*
 * 求1+2+3+...+n,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
 */
public class CountSumByN {
    
    public static int Solution(int n) {
       int sum = n;
         
       boolean flag = (n>0) && ((sum+=Solution(n-1))>0);
         
       return sum;
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.err.println(Solution(3));
    }

}

 

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

标签:blog   turn   for   case   auto   返回   直接   bool   str   

原文地址:http://www.cnblogs.com/liuzhenping/p/7604163.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!