C++ 中兩個數字替換數字後的最大和最小和


給定兩個正數 num1 和 num2。目標是找到這兩個數在替換數字後可能得到的最小和和最大和。我們允許替換這兩個數字中每個數字的數字。假設 num1 是 434,num2 是 324,我們可以將數字 3 替換為 4,將數字 4 替換為 3。那麼最小和將為 - 333+323=656,最大和將為 444+424=864。

讓我們透過示例瞭解數字替換 3 為 4,反之亦然 -

輸入

num1=3224 num2=4321

輸出

Maximum sum is : 8645
Minimum sum is : 6544

解釋 - 將所有 3 替換為 4 以使兩個數字都更大,因為 4 大於 3。

num1 變為 4224,num2 變為 4421,和為 8645 將所有 4 替換為 3 以使兩個數字都更小,因為 3 小於 4。

num1 變為 3223,num2 變為 3321,和為 6544

輸入

num1=3111 num2=4111

輸出

Maximum sum is : 8222
Minimum sum is : 6222

解釋 - 將所有 3 替換為 4 以使兩個數字都更大,因為 4 大於 3。

num1 變為 4111,num2 變為 4111,和為 8222 將所有 4 替換為 3 以使兩個數字都更小,因為 3 小於 4。

num1 變為 3111,num2 變為 3111,和為 6222

下面程式中使用的方案如下

  • 這些數字存在於變數 num1 和 num2 中。

  • 函式 calculateSum ( int n1,int n2) 用於計算數字替換後數字的最小和和最大和。

  • 它以兩個數字 n1 和 n2 作為引數,並顯示儲存在 minSum 和 maxSum 中的結果。

  • 首先,我們將兩個數字中的每個 4 都替換為 3,並將新值分別儲存在 num2 和 num2 中,方法是分別呼叫 replace(n1,4,3) 和 replace(n2,4,3)。

  • 透過新增新的 num1 和 num2 來計算最小和。

  • 類似地,透過呼叫 replace(n1,3,4) 和 replace(n2,3,4) 重複上述步驟以將每個 3 替換為 4,並計算最大和。

  • 函式 replace(int x,int digit1,int digit2) 將 x 中的每個 digit1 替換為 digit2 並返回新數字。

  • 變數 number 儲存新獲得的數字,初始化為 0。

  • temp 用於儲存每次迭代的乘數 10。

  • 我們將透過將 x 除以 10 並將餘數儲存在 rem 中的 remainder 中來從右側獲取每個數字。

  • 如果 rem 等於 digit1,則將其替換為 digit2。將其新增到獲得新數字 = number + digit2 * temp;

  • 否則沒有變化 number=number + rem*temp;

  • 透過將 x 除以 10 並將乘數增加 10 來減少 x。(remp=temp*10)

  • 返回獲得的數字。

示例

 即時演示

#include<bits/stdc++.h>
using namespace std;
//replace digit1 with digit2
int replace(int x, int digit1, int digit2){
   int number = 0;
   int temp = 1;
   while (x > 0){
      int rem = x % 10;
      // Required digit found, replace it
      if (rem == digit1)
         number = number + digit2 * temp;
      else
         number = number + rem * temp;
         temp *= 10;
         x = x / 10;
      }
      return number;
   }
   void calculateSum(int n1, int n2){
      //replace 4 by 3
      int num1=replace(n1,4,3);
      int num2=replace(n2,4,3);
      int minSum=num1+num2;
      //replace 3 by 4
      num1=replace(n1,3,4);
      num2=replace(n2,3,4);
      int maxSum=num1+num2;
      std::cout << "Minimum Sum by digit replacement: " << minSum;
      std::cout << "\nMaximum Sum by digit replacement: " << maxSum;
}
int main(){
   int num1 = 3131, num2 = 4141;
   calculateSum(num1, num2);
   return 0;
}

輸出

Minimum Sum by digit replacement: 6262
Maximum Sum by digit replacement: 8282

更新於: 2020-07-28

274 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.