关注
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
相关推荐
10-23 15:58
华中农业大学 Java
LZStarV:冲就好了,就算真的是字节也冲,面评脏了大不了等三四个月就淡了,而且等到那个时候实力进步了选择还多,何必拘泥于字节 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 找工作能把i人逼成什么样 #
14863次浏览 174人参与
# 上班到公司第一件事做什么? #
109477次浏览 740人参与
# 你今年做了几份实习? #
9912次浏览 145人参与
# 工作两年想退休了 #
203561次浏览 1799人参与
# 你开始找寒假实习了吗? #
16053次浏览 211人参与
# 新凯来求职进展汇总 #
64149次浏览 171人参与
# 影石Insta360求职进展汇总 #
166529次浏览 1335人参与
# 大厂面试初体验 #
83679次浏览 385人参与
# 0经验如何找实习? #
27228次浏览 456人参与
# 面试尴尬现场 #
205478次浏览 821人参与
# 大学最后一个寒假,我想…… #
72300次浏览 727人参与
# 25届秋招公司红黑榜 #
306739次浏览 1252人参与
# 什么样的公司千万别去 #
28085次浏览 148人参与
# 大家每天通勤多久? #
64539次浏览 415人参与
# 金融财经春招备战日记 #
43918次浏览 216人参与
# 央国企投递记录 #
166075次浏览 1622人参与
# 你找工作经历过哪些骗局? #
9845次浏览 144人参与
# 机械人值得去的半导体企业 #
32998次浏览 183人参与
# 字节出了豆包coding模型 #
6894次浏览 61人参与
# 一起聊华为 #
168653次浏览 820人参与
查看13道真题和解析