题解 | #求小球落地5次后所经历的路程和第5次反弹的高度#

求小球落地5次后所经历的路程和第5次反弹的高度

https://www.nowcoder.com/practice/2f6f9339d151410583459847ecc98446

import java.math.BigDecimal;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextInt()) { // 注意 while 处理多个 case
            int initHeght = in.nextInt(); // 初始高度
            System.out.println(String.valueOf(totalHeght(new BigDecimal(initHeght), 1,
                                              BigDecimal.ZERO)));
            System.out.println(String.valueOf(fourHeght(new BigDecimal(initHeght), 1)));
        }
    }

    private static BigDecimal totalHeght(BigDecimal initHeight, int num,
                                         BigDecimal totalHeight) {

        if (BigDecimal.ZERO == initHeight || num > 5 || num == 0) {
            return totalHeight;
        }
        if (num > 0 && num <= 5 ) {
            BigDecimal ftHeght = initHeight.divide(new BigDecimal(2), 6,
                                                   BigDecimal.ROUND_HALF_UP); // 反弹的高度
            if (num == 1) {
                totalHeight = totalHeight.add(initHeight);
            } else {
                totalHeight = totalHeight.add(initHeight.multiply(new BigDecimal( 2))); // 经过的总长度
            } 
            num += 1; // 次数从1开始,到5结束;
            return totalHeght(ftHeght, num, totalHeight);
        }
        return totalHeight;

    }

    private static BigDecimal fourHeght(BigDecimal initHeight, int num) {

        BigDecimal g = initHeight.divide(new BigDecimal(2), 6,
                                         BigDecimal.ROUND_HALF_UP); // 反弹的高度;;
        if ( num == 5 ) {
            return g ; // 反弹的高度;;
        } else {
            return fourHeght(g, num + 1);
        }


    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务