Bit operation and its implementation

The two most commonly used operations for bit operations

What is the k-th bit in the binary representation of n:
First understand the meaning of the bit in binary: In binary, it is marked as 0, 1, 2, 3, etc. from the single digit forward,
as shown in the following figure:
Insert picture description here
The red part indicates the position.
After understanding this step, the next step is to understand the specific operation steps:
1. Move the k-th digit to the single digit, which involves the right shift operation: n >> k
Note: 1010Shift one bit to the right :, Shift two digits to the right 101:, 10three Bit:1

2. The numbers on the output bits, then the numbers of bits k is the digital bits our requirements, x & 1the representative is extracted binary digit x in
summary, the operator need only: n >> k & 1to Can be done

Example: Take out the first three digits of 10

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	int n = 10;
	for(int i = 3; i >= 0; i -- )cout << (n >> i & 1);
	return 0;
}

Lowbit(x) operation

Function : Return the last 1 in the binary code of x. ( The rightmost 1)
For example:

x = 10;//二进制位1010
lowbit(x) = 10
x = 101000;//某数转化为二进制后的形式
lowbit(x) = 1000;

The realization principle of lowbit(x): The
realization principle is: x & -x
Note: In c++, -x is the complement form of x, which is equivalent to the inversion of x plus 1 ( ~x + 1) (both in binary representation).
For example: x = 1001010010000100000000
then ~x = 0110101101111011111111,then~x + 1 = 0110101101111100000000
x & -x = 0000000000000100000000

Practical usage: You can count the number of 1s in x (binary code).
Example:
Given a sequence of length n, please find the number of 1s in the binary representation of each number in the sequence.

Input format The
first line contains the integer n, and the second line contains n integers, representing the entire number sequence.

The output format is
one line, containing n integers, where the i-th number represents the number of 1s in the binary representation of the i-th number in the sequence.

Data range
1≤n≤100000, 0≤value
of elements in the sequence ≤109

Input sample :

5
1 2 3 4 5

Sample output:

1 1 2 1 2
#include<bits/stdc++.h>
using namespace std;
int lowbit(int x)
{
    
    
	return x & -x;
}
int main()
{
    
    
	int n;
	cin >> n;
	while(n -- )
	{
    
    
		int a;
		cin >> a;
		int res = 0;
		while(a) a -= lowbit(a), res ++ ;//每一次当a不为0的时候,就把最后一位的1减去,用res进行计数,最后res的值记为删去的1的个数,也是原数中1的个数
		cout << res << ' ';
	}
}

Guess you like

Origin blog.csdn.net/qq_51960163/article/details/115140579