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

相关推荐

不愿透露姓名的神秘牛友
12-10 15:21
华为-媒体院 算法 n*16 硕士985
点赞 评论 收藏
分享
LZStarV:冲就好了,就算真的是字节也冲,面评脏了大不了等三四个月就淡了,而且等到那个时候实力进步了选择还多,何必拘泥于字节
点赞 评论 收藏
分享
想进开水团喝开水:哦 给我一个 就算你真拿到牛友也会为你开心的
点赞 评论 收藏
分享
牛客网
牛客网在线编程
牛客网题解
牛客企业服务