查找将数字c和d转换为最小操作数的C++代码
假设我们有两个数字c和d。Amal最初有两个数字a和b,它们都为零。Amal希望对它们执行一些操作。在执行每个操作之前,会选择一些正整数k,然后用于执行以下操作之一:
将数字k加到a和b中,或者
将数字k加到a中,并从b中减去k,或者
将数字k加到b中,并从a中减去k。
我们必须找到使a和b分别等于c和d所需的最小操作数。如果不可能,则返回-1。
因此,如果输入类似于c = 3;d = 5,则输出将为2,因为对于k = 1,我们得到数字(1,1),对于k = 8,该对可以是(-7,9),对于k = 7,它可以是(0,2),对于k = 3,它可以是(3,5)
步骤
为了解决这个问题,我们将遵循以下步骤:
if (c ^ d) is odd, then: return -1 otherwise when c is same as 0 and d is same as 0, then: return 0 otherwise when c is same as d, then: return 1 Otherwise return 2
示例
让我们看看以下实现以更好地理解:
#include <bits/stdc++.h>
using namespace std;
int solve(int c, int d){
if ((c ^ d) & 1)
return -1;
else if (c == 0 && d == 0)
return 0;
else if (c == d)
return 1;
else
return 2;
}
int main(){
int c = 3;
int d = 5;
cout << solve(c, d) << endl;
}输入
3, 5
输出
2
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP