import java.util.Scanner; public class Main { /** * 蚂蚱跳跃次数 *  * @param desPoint * @return */ public static int jumpCount(int desPoint) { int currentJumpPosition = 0;// 当前跳跃的位置 int jumpStep = 0;// 跳跃步进 int jumpCount = 0;// 跳跃次数 while (currentJumpPosition != desPoint) {// 循环,往一个方向跳跃 if (desPoint > 0) jumpStep += 1; // 正方向 else { jumpStep += -1;// 反方向 } jumpCount++; currentJumpPosition += jumpStep;// 加上步长 // 超过了 if ((desPoint > 0 && currentJumpPosition > desPoint) || (currentJumpPosition < desPoint && desPoint < 0)) { jumpCount--;// 减一 currentJumpPosition -= jumpStep;// 减去步进 jumpStep -= 1;// 减一 boolean isForward = false;// 往后 if (desPoint < 0) { isForward = true;     // 往前 } while (currentJumpPosition != desPoint) {// 来回跳跃,直到达到终点 jumpCount++; if (isForward) {// 往前跳 if (jumpStep > 0) { jumpStep = jumpStep + 1; } else { jumpStep = -jumpStep + 1; } } else { // 往后跳 if (jumpStep > 0) { jumpStep = -jumpStep - 1; } else { jumpStep = jumpStep - 1; } } isForward = !isForward;// 取反 currentJumpPosition += jumpStep;// 加上步长 } } } return jumpCount; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int desPoint = scanner.nextInt();// 目标位置 System.out.println(jumpCount(desPoint)); } } } AC 17%
点赞 2

相关推荐

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