求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 文章被收录于专栏
为刷过的每一道题都书写一篇题解,便于重复练习~