关注
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
相关推荐
点赞 评论 收藏
分享
01-16 11:36
西北工业大学 C++ 点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 在大厂上班是一种什么样的体验 #
11216次浏览 142人参与
# 你的mentor是什么样的人? #
50877次浏览 716人参与
# 程序员找工作至少要刷多少题? #
19471次浏览 253人参与
# 我和mentor的爱恨情仇 #
106024次浏览 942人参与
# 论秋招对个人心气的改变 #
11679次浏览 167人参与
# 校招第一份工作你干了多久? #
136524次浏览 597人参与
# 机械人避雷的岗位/公司 #
43673次浏览 302人参与
# 设计人如何选offer #
189547次浏览 868人参与
# 为了减少AI幻觉,你注入过哪些设定? #
5072次浏览 155人参与
# 你的秋招进行到哪一步了 #
2530061次浏览 23253人参与
# 机械人还在等华为开奖吗? #
312009次浏览 1582人参与
# 牛客AI体验站 #
7039次浏览 192人参与
# 重来一次,我还会选择这个专业吗 #
411095次浏览 3898人参与
# 我现在比当时_,你想录用我吗 #
8938次浏览 114人参与
# 12306一秒售罄,你抢到回家的票了吗? #
2084次浏览 48人参与
# 一张图晒一下你的AI员工 #
5316次浏览 120人参与
# AI Coding的使用心得 #
4827次浏览 102人参与
# 刚入职的你踩过哪些坑 #
7121次浏览 130人参与
# 关于春招/暑期实习,你想知道哪些信息? #
7789次浏览 121人参与
# 应届生进小公司有什么影响吗 #
118370次浏览 1159人参与
