上海计算机学会2022年11月月赛C++丙组T2搭积木

搭积木

内存限制: 256 Mb时间限制: 1000 ms

题目描述

小爱用积木搭起一座金字塔。为了结构稳定,金字塔的每一层要比上一层多一块积木。规则如下:

  • 第 1 层需要放 1 块积木
  • 第 2 层需要放 2 块积木
  • 第 3 层需要放 3 块积木
  • 第 i 层需要放 i 块积木

给定积木的数量 n,请问最高可以搭出多少层的金字塔?

输入格式

单个整数表示 n

输出格式

单个整数表示金字塔的最高高度。

数据范围
  • 对于 50% 的数据,1≤n≤1,000
  • 对于 100% 的数据,1≤n≤1,000,000,000
样例数据

解析:

详见代码:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    int ans = 0;
    cin >> n;
    for (int i = 1; i == i; i++) {
        if (n >= i) {//剩下的积木够搭第i层
            n -= i;//用掉i块积木搭第i层
            ans = i;//可以搭i层
        } else {//不够,退出循环
            break;
        }
    }
    cout << ans << endl;
    return 0;
}

简化版:

#include <bits/stdc++.h>
using namespace std;
 
int main() {
    int n;
    int ans = 0;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        n -= i;//用掉i块积木搭第i层
        ans = i;//可以搭i层
    }
    cout << ans << endl;
    return 0;
}

 再简化版:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n, i;
    cin >> n;
    for (i = 1; i <= n; i++) {
        n -= i;//用掉i块积木搭第i层
    }
    cout << i - 1 << endl;
    return 0;
}

另一种解法:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    int ans = 0;
    int i = 0;
    int sum = 0;//用掉的积木
    cin >> n;
    while (sum <= n) {
        i++;
        sum += i;
        ans++;
    }
    cout << ans - 1 << endl;
    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

长春高老师信奥工作室

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值