关注
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
相关推荐
查看3道真题和解析 点赞 评论 收藏
分享
牛客热帖
更多
- 1... 我进字节她考编,明知要分手但确没人敢开口1.3W
- 2... 非科班+本科目前正在做AI工程师,说说我这3年。。。1.3W
- 3... 我的求职总结 | 致那个一边崩溃一边投简历的自己,赢现金奖励!9111
- 4... 26届,五月,0 offer,0保底,0面试,收拾收拾准备送外卖5304
- 5... 海力士总市值突破9000亿美元,国内能赌哪些公司?5273
- 6... 27腾讯云智暑期面经4452
- 7... 实习一周天天给+1买咖啡买饭,不给钱!!4202
- 8... 被妈妈说的感觉自己好没用啊😭4087
- 9... 偷了同事简历,有字节暑实面试了3399
- 10... 云智hr面不是结束,而是开始3224
正在热议
更多
# AI让海力士市值突破9000亿美元 #
6565次浏览 55人参与
# 如何排解工作中的焦虑 #
339722次浏览 2875人参与
# 在爱玛,骑向未来 #
47858次浏览 458人参与
# 我的求职总结 #
467774次浏览 6647人参与
# 牛油的搬砖plog #
203807次浏览 1313人参与
# 机械笔面试考察这些知识点 #
20478次浏览 156人参与
# 这些公司卡简历很严格 #
106137次浏览 452人参与
# 国企vs私企,怎么选? #
52245次浏览 233人参与
# 职场新人体验 #
194273次浏览 1266人参与
# 哪些公司对双非友好 #
236790次浏览 1261人参与
# 机械人与华为的爱恨情仇 #
161023次浏览 1060人参与
# 求职低谷期你是怎么度过的 #
41945次浏览 370人参与
# 什么专业适合考公 #
70646次浏览 390人参与
# 百度工作体验 #
337522次浏览 2295人参与
# 软开人,秋招你打算投哪些公司呢 #
204228次浏览 1584人参与
# 硬件人求职现状 #
538629次浏览 4838人参与
# 打工人的精神状态 #
156185次浏览 1581人参与
# 面试尴尬现场 #
228954次浏览 873人参与
# 设计人如何选offer #
214216次浏览 888人参与
# 海康威视求职进展汇总 #
612955次浏览 3774人参与
# 游戏求职进展汇总 #
794064次浏览 6522人参与
