將兩個數字的交替位合併以生成一個新數字(C++)


在本文中,我們需要使用兩個數字的交替位來生成一個數字。所以,本文中我們將使用第二個數字的第一位,然後使用第一個數字的第二位,然後再次使用第二個數字的第三位,然後使用第一個數字的第四位,以此類推。

從第一個數字的第一位開始,再取第二個數字的第三位並繼續以此類推。

我們舉個例子來更好地理解這個主題,

Input : n = 6 m = 10
Output : 2
Explanation :
Bits representation of 6 = 0110
Bit representation of 10 = 1010
0 1 1 0
^ ^
1 0 1 0
^ ^
= 0 0 1 0 = 2

現在,透過這個例子,要點非常明確,即我們需要做什麼才能解決程式碼。基本上,解決方案是從第二個數字的 LSB 開始,從數字中獲取交替位。

解決這個問題的一種可行方法是找到第一個數字n的設定偶數位,然後找到第二個數字m的設定奇數位,並返回兩者進行按位或運算。

演算法

Step 1 : For n find the value of set even bits.
Step 2 : For m find the value of set odd bits.
Step 3 : Calculate the result = set even bits of n | set odd bits of m.
Step 4: Print the value of result.

示例

 實際演示

#include <iostream>
using namespace std;
int setevenbits(int n) ;
int setoddbits(int m) ;
int main(){
   int n = 12;
   int m = 17;
   int setn = setevenbits(n);
   int setm = setoddbits(m);
   int result = ( setn | setm );
   cout<<result;
   return 0;
}
int setevenbits(int n){
   int temp = n;
   int count = 0;
   int res = 0;
   for (temp = n; temp > 0; temp >>= 1) {
      if (count % 2 == 1)
         res |= (1 << count);
      count++;
   }
   return (n & res);
}
int setoddbits(int m){
   int count = 0;
   int res = 0;
   for (int temp = m; temp > 0; temp >>= 1) {
      if (count % 2 == 0)
         res |= (1 << count);
      count++;
   }
   return (m & res);
}

輸出

25

更新時間:2019-10-16

120 views

啟動你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.