题目

问题描述

小R有nn部电脑,每部电脑的电池容量分别为aiai​。她可以使用两种不同的充电方式来给电脑充电:

普通充电:每单位时间为电脑充电xx单位的电量。
闪充:每单位时间为电脑充电4x4x单位的电量。

现在,所有电脑的电量都为零。小R希望使用闪充给所有电脑充满电,计算她需要的总充电时间。请保留结果的小数点后两位。
测试样例

样例1:

输入:n = 4 ,x = 1 ,a = [2, 3, 4, 5]
输出:'3.50'

样例2:

输入:n = 3 ,x = 2 ,a = [4, 6, 8]
输出:'2.25'

样例3:

输入:n = 2 ,x = 1 ,a = [10, 5]
输出:'3.75'

代码

import java.text.DecimalFormat;

public class Main {
public static String solution(int n, int x, int[] a) {
// 闪充速率是普通充电速率的4倍
int fastChargeRate = 4 * x;

    // 初始化总充电时间
    double totalChargeTime = 0.0;
    
    // 计算每台电脑充满电所需的时间,并累加到总充电时间
    for (int capacity : a) {
        double chargeTime = (double) capacity / fastChargeRate;
        totalChargeTime += chargeTime;
    }
    
    // 格式化结果保留两位小数
    DecimalFormat df = new DecimalFormat("0.00");
    return df.format(totalChargeTime);
}

public static void main(String[] args) {
    // 测试用例
    System.out.println(solution(4, 1, new int[]{2, 3, 4, 5}).equals("3.50"));  // 应该输出 true
    System.out.println(solution(3, 2, new int[]{4, 6, 8}).equals("2.25"));    // 应该输出 true
    System.out.println(solution(2, 1, new int[]{10, 5}).equals("3.75"));      // 应该输出 true
    
    // 添加更多测试用例
    System.out.println(solution(12, 4, new int[]{10, 16, 4, 7, 7, 3, 8, 1, 5, 13, 10, 6}).equals("5.62"));  // 应该输出 true
}

}

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐