搭积木
内存限制: 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;
}