首先如果x==y,不需要操作。
如果只执行一次操作二让x和y相等,只有当y=0的情况,所以当y=0时只需要一次操作。同理,当x==0时,可以通过操作一+操作二实现。
考虑两次操作二,x和y分别变为2x, 2y, 这并没有改变什么,考虑两次操作二中加入一次操作一,x和y分别变为2x,-2y,所以第三种情况只有当x和y是相反数的时候才能满足。否则怎么都无法实现x和y相等,输出-1
Java
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x = scanner.nextInt();
        int y = scanner.nextInt();
        if (x == y) {
            System.out.println(0);
        } else if (y == 0) {
            System.out.println(1);
        } else if (x == 0) {
            System.out.println(2);
        } else if (x == -y) {
            System.out.println(3);
        } else {
            System.out.println(-1);
        }
    }
}
C++
#include <iostream>
using namespace std;
int main() {
    int x, y;
    cin >> x >> y;
    if (x == y) {
        cout << 0 << endl;
    } else if (y == 0) {
        cout << 1 << endl;
    } else if (x == 0) {
        cout << 2 << endl;
    } else if (x == -y) {
        cout << 3 << endl;
    } else {
        cout << -1 << endl;
    }
    return 0;
}
Python
x, y = map(int, input().split(' '))
if x == y:
    print(0)
elif y == 0:
    print(1)
elif x == 0:
    print(2)
elif x == -y:
    print(3)
else:
    print(-1)
会员可通过查看《已通过》的提交记录来查看其他语言哦~
给出两个整数X,Y,你可以任意顺序多次执行以下两个操作。求出使得X=Y时所需的最少操作次数。如果无法实现,则输出-1
令经过一次操作后X和Y的值分别为X′和Y′
操作一:X′=Y,Y′=X
操作二:X′=X+Y,Y′=X−Y
输入的第一行给出两个整数X,Y
−100≤X,Y≤100
输出使得X=Y时所的最少得作次教,如果无法实现,则输出-1
输入
5 8
输出
-1
输入
5 -5
输出
3