求1+2+3+···+n

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

https://www.nowcoder.com/practice/7a0da8fc483247ff8800059e12d7caf1?tpId=13&&tqId=11200&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

循环相加

public class Solution {
    public int Sum_Solution(int n) {
        int sum = n;
        for(int i = 1; i < n; i++){
            sum+=i;
        }
        return sum;
    }
}

递归

public class Solution {
    public int Sum_Solution(int n) {
        if(n == 1)
            return n;
        return n+Sum_Solution(n-1);
    }
}

变形递归

public int Sum_Solution(int n) {
        int sum = n; 
        boolean result = (n > 0) && ((sum += Sum_Solution(n-1)) > 0); 
        return sum;
    }
剑指offer 文章被收录于专栏

为刷过的每一道题都书写一篇题解,便于重复练习~

全部评论

相关推荐

牛客42479632...:多投吧 我学c++就学了3个月都找到好几家实习了
点赞 评论 收藏
分享
notbeentak...:孩子,说实话,选择很重要,可能你换一个方向会好很多,但是现在时间不太够了,除非准备春招
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务