首页 > 编程语言 > 详细

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

时间:2020-03-20 15:37:40      阅读:86      评论:0      收藏:0      [点我收藏+]

/*
求1+2+3+...+n,
要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
*/
//解题思路:对于A && B,如果A为假,那么就不执行B了;而如果A为真,就会执行B。
//对于A || B,如果A为真,那么就会不执行B了;而如果A为假,就会执行B。
//逻辑运算符了,有短路特性的话,就可以当作if来使用了。
public class Class53 {

public int Sum_Solution(int n){
int sum = n;
boolean index = (n > 1) && ((sum += Sum_Solution(n - 1)) > 0); //if(n > 1){sum += Sum_solution(n - 1);}
return sum;
}
public void test(){
int n = 10;
System.out.println(Sum_Solution(n));
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Class53 c = new Class53();
c.test();

}

}

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

原文:https://www.cnblogs.com/zhuozige/p/12531420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!