scala交换数组相邻两位
Problem statement: C++ program to swap all odd bits with even bits (swap adjacent bits). Every even positiC++ program to swap all odd bits with even bits (swap adjacent bits). Every even position bit is swapped with an adjacent bit on the right side and every odd position bit is swapped with adjacent on the left side. For instance, 13(00001101) should be converted to 14(00001110) .on bit is swapped with an adjacent bit on the right side and every odd position bit is swapped with adjacent on the left side. For instance, 13(00001101) should be converted to 14(00001110).
问题陈述: C ++程序将所有奇数位与偶数位交换(交换相邻位)。 每个偶数positiC ++程序都将所有奇数位与偶数位交换(交换相邻位)。 每个偶数位与右侧的相邻位交换,而每个奇数位与左侧的相邻位交换。 例如,应将13(00001101)转换为14(00001110)。on位置的位与右侧的相邻位交换,而每个奇数位置位的位置与左侧的相邻位交换。 例如,应该将13(00001101)转换为14(00001110)。
Input format: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains an unsigned integer N.
输入格式:输入的第一行包含一个整数T,它表示测试用例的数量。 然后是T测试用例。 每个测试用例的第一行包含一个无符号整数N。
Output format: Corresponding to each test case, print in a new line, the converted number.
输出格式:对应每个测试用例,在新行中打印转换后的数字。
Constraints:
限制条件:
1 ≤ T ≤ 100
1 ≤ N ≤ 100
Example:
例:
Input:
2
13
2
Output:
Original number is : 13
Converted number is : 14
Original number is : 2
Converted number is : 1
Explanation:
说明:
If the original number is 13 (00001101), then bits at odd and even position are swapped in following manner.
如果原始数字为13(00001101),则奇数和偶数位置的位将按以下方式交换。
After swapping, the bits are:
交换之后,这些位是:
Algorithm:
算法:
Create a mask to obtain the 0xAAAAAAAA to extract bits.
创建一个掩码以获得0xAAAAAAAA来提取位。
Obtain the odd bits and shift these to even positions.
获取奇数位并将其移位到偶数位置。
Either create mask2 (0x55555555) for even bits or right shift the mask to extract it. Obtain the even bits and shift these to odd positions.
为偶数位创建mask2(0x55555555),或右移掩码以将其提取。 获取偶数位并将其移至奇数位置。
Combine the shifted values of odd and even bits to obtain the converted number.
组合奇数位和偶数位的移位值以获得转换后的数字。
Program:
程序:
#include <iostream>
using namespace std;
unsigned int swap_odd_even(int num){
int mask=0xAAAAAAAA;
//A in hexadecimal is equal to 10 in decimal
//and 1010 in binary
unsigned int oddbits = (num&mask);
//right shift for even bits
unsigned int evenbits = num&(mask>>1);
//can also use 0x55555555 as mask for even bits
return (oddbits>>1) | (evenbits<<1);
}
int main()
{
int T; //testcases
cout<<"Enter total number of elements (test cases): ";
cin>>T;
//variable to store the number
unsigned int N;
for(int i=0;i<T;i++)
{
cout<<"Enter number: ";
cin>>N;
cout<<"Original number is : "<<N<<endl;
cout<<"Converted number is :"<<swap_odd_even(N)<<endl;
}
return 0;
}
Output
输出量
Enter total number of elements (test cases): 2
Enter number: 13
Original number is : 13
Converted number is :14
Enter number: 2
Original number is : 2
Converted number is :1
翻译自: https://www.includehelp.com/cpp-programs/swap-adjacent-bits.aspx
scala交换数组相邻两位