和我一起迎接明天的太阳吧

klaus08

焦虑源于行动的匮乏

JZ47 求1+2+3+...+n

原题链接


描述

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


示例

输入:5
返回值:15

思路

题目本身简单,但是加上限制条件就不好做了。不用for、whille,只有递归解决了,但是 if 也不能用,递归的返回条件就不能实现了。这时候用到&&,它和&的区别就是多了一个短路的功能,这样就可以用ConditionA && ConditionB代替if(ConditionA) {ConditionB}的操作了。


解答

public class Solution {
    public int Sum_Solution(int n) {
        boolean tmp = n > 1 && (n += Sum_Solution(n - 1)) > 0;
        return n;
    }
}

/**********递归版本,用于参考*************/
public int Sum_Solution(int n) {
    if (n == 1) return n;
    return n + Sum_Solution(n - 1);
}
posted @ 2021-08-22 23:16  klaus08  阅读(26)  评论(0编辑  收藏  举报