【面试真题】设计一个抢红包算法,单个红包最大不能超过总金额的90%

题干:

总金额 double total = 100D;    
总人数 int num = 10;
返回一个List<Double>

参考代码:

public class RedWars {
    
    

    public static List<Double> list = new ArrayList<>(10);
    public static double remain;
    public static double used;

    public static List<Double> solution(double total, int num) {
    
    
        if (num < 2) {
    
    
            list.add(remain);
            return list;
        }
        Random random = new Random();
        double bound = random.nextInt(91) / 100.0;
        remain = total;
        used = remain * bound;
        BigDecimal b0 = new BigDecimal(used);
        used = b0.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        Math.round(used);
        list.add(used);
        remain = remain - used;
        BigDecimal b1 = new BigDecimal(remain);
        remain = b1.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        return solution(remain, --num);

    }

    public static void main(String[] args) {
    
    
        double total = 100;
        int num = 10;
        List<Double> solution = solution(total, num);
        System.out.println(solution);
    }


}

输出:

[33.0, 43.55, 7.03, 13.96, 1.21, 0.98, 0.02, 0.18, 0.0, 0.07]

猜你喜欢

转载自blog.csdn.net/haohaoxuexiyai/article/details/123125556