小东和三个朋友一起在楼上抛小球,他们站在楼房的不同层,假设小东站的楼层距离地面N米,球从他手里自由落下,每次落地后反跳回上次下落高度的一半,并以此类推直到全部落到地面不跳,求4个小球一共经过了多少米?(数字都为整数)
给定四个整数A,B,C,D,请返回所求结果。
测试样例:
100,90,80,70
返回:1020
import java.util.*; public class Balls { public int calcDistance(int A, int B, int C, int D) { // write code here double dist = A + B + C + D; double sum = dist; while( dist > 0){ sum += dist; dist /= 2; } // int result = (int)Math.ceil(sum); int result = (int)3*(A+B+C+D); return result; } }
import java.util.*; public class Balls { public static int calcDistance(int A, int B, int C, int D) { // write code here //对double类型的返回结果 向上取整 return (int)Math.ceil(oneBallDis(A) + oneBallDis(B) + oneBallDis(C) + oneBallDis(D)); } public static double oneBallDis(int n){ //使用double类型的变量存储单个小球的运动距离 double distance = n; double temp = n *1.0 / 2; while(temp > 0){ distance += temp * 2; temp = temp / 2; } return distance; } }
import java.util.*; public class Balls { public int calcDistance(int A, int B, int C, int D) { // write code here return (int)(Math.round(distance(A)+distance(B)+distance(C)+distance(D))); } public static double distance(int A){ double d= A; double sum =2*A; while(d>=0.01){ d/=2; sum+=d; } return sum; } }