美文网首页
1到100的和

1到100的和

作者: 丹之 | 来源:发表于2018-10-04 17:39 被阅读0次
   int total = 0;// 总和
    // 非递归算法,时间复杂度O(n),空间复杂度O(1)
    public int addtion_0(int n) {
        for (int i = 0; i <= n; i++) {
            total += i;
        }
        return total;
    }
    // 递归算法,时间复杂度为O(n),空间复杂度为O(n)
    public int addtion(int n) {
        if (n == 1)
            return 1;
        else {
            return total = total + n + addtion(n - 1);
        }
    }
    // 利用等差数列求和公式,时间复杂度为O(1),空间复杂度为O(1)
    public int addtion02(int n) {
        return n * (1 + n) / 2;
    }

相关文章

网友评论

      本文标题:1到100的和

      本文链接:https://www.haomeiwen.com/subject/tcgxaftx.html