public class Main { public static int solution(int x_position, int y_position) { int step=0; if(y_position < x_position){ //互换值 int temp = x_position; x_position = y_position; y_position= temp; } else if(x_position == y_position){ return 0; } int mid = (y_position-x_position)/2; int an = 1,Sn = 1; int i=0,n=1; int remain; //记录剩余距离
while(Sn <= mid){
an +=1;
n++;
Sn += an;
}
// printf("n=%d Sn=%d an=%d",n,Sn,an);
Sn -= an;
an -= 1; //还原
step = 2*(n-1); //目前走的步数
int k;
//*2说明还可以再走一个an+1 */
if((mid-Sn)*2 > an){
k = an + 1;
step += 1; //如果中间还能走一步,还有多
remain = (y_position-x_position)-Sn*2 - k;
}else if((mid-Sn)*2 == an){
k = an;
step += 1; //如果中间刚好走一步
remain = (y_position-x_position)-Sn*2 - k;
}
else{
k = an;
remain = (y_position-x_position)-Sn*2;
}
if((y_position-x_position)%2 == 1){ //如果是奇数
remain += 1;
}
// printf(" k=%d remain=%d",k,remain) ;
if(remain > k){
step += 2;
}else if(remain > 1){
step += 1;
}else if(remain == 0){
//不用额外加步数
}
return step;
}
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);
}
}