题解 | #求小球落地5次后所经历的路程和第5次反弹的高度#
求小球落地5次后所经历的路程和第5次反弹的高度
https://www.nowcoder.com/practice/2f6f9339d151410583459847ecc98446
解题思路
- 对于总路程:
- 第1次:下落
- 第2次:反弹
+ 下落
- 第3次:反弹
+ 下落
- 第4次:反弹
+ 下落
- 第5次:反弹
+ 下落
- 第1次:下落
- 第5次反弹高度就是初始高度除以2的5次方
def calculate_ball_path(height):
# 计算第5次反弹高度
final_height = height / (2 ** 5)
# 计算总路程
total_distance = height # 第一次落地
for i in range(4): # 后续4次弹跳
bounce_height = height / (2 ** (i + 1))
total_distance += bounce_height * 2 # 上升+下降的距离
return total_distance, final_height
def main():
height = float(input())
distance, final_height = calculate_ball_path(height)
print(f"{distance}")
print(f"{final_height}")
if __name__ == "__main__":
main()
import java.util.Scanner;
public class Main {
public static double[] calculateBallPath(double height) {
// 计算第5次反弹高度
double finalHeight = height / Math.pow(2, 5);
// 计算总路程
double totalDistance = height; // 第一次落地
for (int i = 0; i < 4; i++) { // 后续4次弹跳
double bounceHeight = height / Math.pow(2, i + 1);
totalDistance += bounceHeight * 2; // 上升+下降的距离
}
return new double[]{totalDistance, finalHeight};
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double height = scanner.nextDouble();
double[] result = calculateBallPath(height);
System.out.println(result[0]);
System.out.println(result[1]);
scanner.close();
}
}
#include <iostream>
#include <cmath>
using namespace std;
pair<double, double> calculateBallPath(double height) {
// 计算第5次反弹高度
double finalHeight = height / pow(2, 5);
// 计算总路程
double totalDistance = height; // 第一次落地
for (int i = 0; i < 4; i++) { // 后续4次弹跳
double bounceHeight = height / pow(2, i + 1);
totalDistance += bounceHeight * 2; // 上升+下降的距离
}
return {totalDistance, finalHeight};
}
int main() {
double height;
cin >> height;
auto [distance, finalHeight] = calculateBallPath(height);
cout << distance << endl;
cout << finalHeight << endl;
return 0;
}
算法分析
- 算法:简单数学计算
- 时间复杂度:
- 只需固定次数的计算
- 空间复杂度:
- 只使用常数额外空间