将两个数字的交替位合并以生成一个新数字(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
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP