校招算法笔面试 | 华为机试-求小球落地5次后所经历的路程和第5次反弹的高度

题目

题目链接

解题思路

  1. 对于总路程:
    • 第1次:下落 h h h
    • 第2次:反弹 ( h / 2 ) (h/2) (h/2) + 下落 ( h / 2 ) (h/2) (h/2)
    • 第3次:反弹 ( h / 4 ) (h/4) (h/4) + 下落 ( h / 4 ) (h/4) (h/4)
    • 第4次:反弹 ( h / 8 ) (h/8) (h/8) + 下落 ( h / 8 ) (h/8) (h/8)
    • 第5次:反弹 ( h / 16 ) (h/16) (h/16) + 下落 ( h / 16 ) (h/16) (h/16)
  2. 第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;
}

算法分析

  • 算法:简单数学计算
  • 时间复杂度: O ( 1 ) \mathcal{O}(1) O(1) - 只需固定次数的计算
  • 空间复杂度: O ( 1 ) \mathcal{O}(1) O(1) - 只使用常数额外空间
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值