第一次借助AI做题记录| 豆包MarsCode AI 刷题

49 阅读1分钟

第一次尝试掘金社区的AI刷题,做题旁边有个小助手来帮助你,觉得挺有意思,我们随机来拿一道题来试一下

[39] 计算从位置 x 到 y 的最少步数

问题描述:

小F正在进行一个 AB 实验,需要从整数位置 x 移动到整数位置 y。每一步可以将当前位置增加或减少,且每步的增加或减少的值必须是连续的整数(即每步的移动范围是上一步的 -1+0 或 +1)。首末两步的步长必须是 1。求从 x 到 y 的最少步数。

输入描述

输入包含两个整数 x 和 y,表示起始位置和目标位置。

输出描述

输出从 x 到 y 所需的最小步数。

测试样例

样例1:

输入:x_position = 12, y_position = 6
输出:4

样例2:

输入:x_position = 34, y_position = 45
输出:6

样例3:

输入:x_position = 50, y_position = 30
输出:8

样例4:

输入:x_position = 0, y_position = 0
输出:0

提供代码思路

如果你一开始没有很好的理解题意,可以借助AI来帮助更好地理解

image.png

完整答案

根据AI提示出来的信息,我们可以很容易地写出答案

public class Main {
    public static int solution(int xPosition, int yPosition) {
        int diff = Math.abs(xPosition - yPosition);
        if (diff == 0) {
            return 0;
        }
        int k = (int)Math.floor(Math.sqrt(diff));
        long kSre= (long)k * k;
        if (kSre < diff) {
          
            long remaining = diff - kSre;
            long extraSteps = (remaining + k -1) / k;
            return 2 * k -1 + (int)extraSteps;
        } else {
            return 2 * k -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);
    }
}