青训营 X 豆包MarsCode 技术训练营--充电总时间计算

题目

问题描述

小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
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值