public class Main {
public static int solution(int xPosition, int yPosition) {
int diff = (yPosition - xPosition);// 计算差值
if(diff < 0)diff *= -1;
int steps = 0; // 初始化步数
int begin = 0;// 初始化当前位置
int step = 1;//初始化步长
// 循环直到到达目标位置
while (begin < diff / 2) {
begin += step;
step++;
steps++;
}
if(begin == diff / 2){
return steps * 2;
}else if( (diff - 2 * (begin - step)) > step ){
return steps * 2;
}else return steps * 2 - 1;
}
public static void main(String[] args) {
// You can add more test cases here
System.out.println(solution(12, 6) == 4);
System.out.println(solution(34, 45) == 6);
System.out.println(solution(50, 30) == 8);
}
}
简单题,多种解法,这里是对能出现的所有三种情况进行判断,
从零开始累加,大于或者等于总长度德一半停止累加:
等于总长度的一半 = 直接乘以2
大于总长度的一半时,判断多出来的长度是否等于最后一步步长
大于最后一步步长: (例如1 2 3 2 2 1 中,当累加到3时,大于总长度的一般,多出来的长度=11 - 2 * (1 + 2 )= 5 > 3 所以一步走不完,要拆成两步)
等于最后一步步长:(*2-1)
最后代码可以更加简洁:
public class Main {
public static int solution(int xPosition, int yPosition) {
int diff = (yPosition - xPosition);// 计算差值
if(diff < 0)diff *= -1;
int steps = 0; // 初始化步数
int begin = 0;// 初始化当前位置
int step = 1;//初始化步长
// 循环直到到达目标位置
while (begin < diff / 2) {
begin += step;
step++;
steps++;
}
if( (diff - 2 * (begin - step)) == step )
return steps * 2 - 1;
return steps * 2;
}
public static void main(String[] args) {
// You can add more test cases here
System.out.println(solution(12, 6) == 4);
System.out.println(solution(34, 45) == 6);
System.out.println(solution(50, 30) == 8);
}
}
通过截图: