求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 文章被收录于专栏

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

全部评论

相关推荐

昨天 21:57
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
程序员小白条:主要没亮点,项目也是网上的,平平无奇,那只能海投了,奖项总得有一些,然后就是现在最好是前后端都会,自己能做项目并且运维的,要么找星球项目改改,要么找个开源项目改改,自己能拓展功能才是主要的,跟做效率很低很低
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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