查詢將數字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

更新於: 2022年3月11日

263次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告