top1编程
← 返回题目
题解

【入门】数数小木块

1 条题解

  • 0
    @ 2026-7-31 4:58:02

    解题思路

    这堆木块是按层堆叠的:

    • 第 1 层:1 块
    • 第 2 层:1+2 = 3 块
    • 第 3 层:1+2+3 = 6 块
    • ……
    • 第 n 层:1+2+...+n = n×(n+1)/2 块

    总数量就是各层之和。

    参考代码

    #include <iostream>
    using namespace std;
    
    int main() {
        int n;
        cin >> n;
    
        int total = 0;
        for (int i = 1; i <= n; i++) {
            total += i * (i + 1) / 2;
        }
        cout << total << endl;
        return 0;
    }
    

    复杂度分析

    • 时间复杂度:O(N)
    • 空间复杂度:O(1)
    • 1