Meet blue bridge, meet you, not negative code, not negative Qing!
catalogue
catalogue
1, Bitwise operators summary overview
5. Supplementary understanding of shift operation
3. Move right without symbol > > >
6. Supplementary understanding of the original code and the inverse code
2, Blue bridge cloud class: the ingenious technique of bit operation
1. Judging odd and even numbers
2. Determine whether the binary bit is 1 or 0 (two methods)
Method 1 problem solving ideas
Method 2 problem solving ideas
3. Exchange the values of two integer variables (XOR)
4. Find the absolute value of an integer without judgment statements
Example 1: how to find the only paired number in the array
Example 2. Find out the number that is left alone
Example 3. Number of 1 in binary
Method 1 problem solving ideas
Method 2 problem solving ideas
Method 3 problem solving ideas
Example 4. Is it an integer power of 2
Example 5: swap parity bits of integers
Thinking questions: K times and once
4, Blue bridge conclusion: meet blue bridge meet you, not negative code, not negative Qing!
[preface]: the author sorted out the notes according to the video officially released by the Blue Bridge Cup. The blog is secondary sorted out from the notes, which has strong pertinence. The little partners who intend to participate in the competition follow the author! In order to facilitate more iron juice, the author uses C language in the code example.
[friendly tip]: in the next two and a half months, bloggers will continue to launch two series of blog posts, one is to solve the C language with zero foundation, and the other is the Blue Bridge Cup algorithm competition, including some feelings and summaries of problem brushing. Of course, there will be a summary of the real problem of the Blue Bridge Cup in previous years. Favorite ironjuice can pay attention to the author.
1, Bitwise operators summary overview
1. Bitwise AND&
If both binary bits are 1, the result is 1, otherwise it is 0
2. Bitwise OR|
If both binary bits are 0, the result is 0, otherwise it is 1
3. Bitwise inversion~
If the bit is 0, it becomes 1, otherwise it becomes 0
4. Bitwise XOR^
If the binary bits of two numbers are the same, the result is 0, and if they are different, the result is 1
5. Supplementary understanding of shift operation
In practical application, we can use left shift / right shift to do fast multiplication and division according to the situation, so the efficiency will be much higher.
1. Move left<<
Don't use the leftmost side, and fill 0 directly on the rightmost side; (shifting left is equivalent to multiplication. For example, shifting left by 1 bit is equivalent to multiplying by 2 to the power of 1)
2. Move right > >
Shift right is equivalent to Division
Because unsigned right shift is not specially introduced in C language, the right shift in C language is divided into arithmetic right shift and logical right shift.
Arithmetic right shift is the rightmost bit. No, the leftmost bit is directly supplemented with the symbol bit (arithmetic right shift is adopted on most machines)
Therefore, the application of shift right in C language needs to pay special attention to negative numbers.
Logical shift to the right means that the rightmost side is not needed, and the leftmost side is directly supplemented with 0
Note: for int type data, when the shift exceeds 32 bits, 32 bits on the module are required, such as 1 < < 35 = = 1 < < 3;
For the long type, 64 modulo (modulo -- > remainder) is required when exceeding
3. Move right without symbol > > >
The unsigned right shift in Java is introduced. It has been used in the same way as the left shift, that is, logical right shift, not on the far right, and 0 on the far left
6. Supplementary understanding of the original code and the inverse code
1. Original code
This number can be directly translated into binary in the form of positive and negative numbers
2. Inverse code
The sign bit of the original code remains unchanged, and other bits can be reversed by bit
3. Complement
The complement can be obtained by inverse code + 1
Note: the original code, inverse code and complement of positive and unsigned numbers are the same. Only the inverse code and complement of negative numbers can be calculated as above
int a = 20; //Integer a is 4 bytes, 32 bits // 00000000 00000000 00010100 - original code // 00000000 00000000 00010100 - inverse code // 00000000 00000000 00010100 - complement int b = -10; // 10000000 0000000 00000000 00001010 - original code // 11111111111111111111111111111110101 - inverse code // 11111111111111111111111111111110110 - complement
Statement: the data storage is only briefly introduced here, and the detailed introduction will be put in the C language series
2, Blue bridge cloud class: the ingenious technique of bit operation
1. Judging odd and even numbers
Problem solving ideas:
Take int for ex amp le. Int takes up 4 bytes, that is, 32 bits. For integer, data is stored in memory in its complement form. Since the numbers in front of the first bit (pay attention to the position of the first bit in the above picture) are 1 and above of 2, only when the first bit is 1, it is odd and 0 is even. After you understand the above sentence first, If we want to judge the parity of an integer, we only need to perform bitwise & operation with 1. Because every bit in 1 except the first bit is 0, and because every bit in any number performs & operation with bit 0 in 1, and the bit result of & operation with bit 0 is 0, the & operation with even number and 1 is 0, and the & operation with odd number and 1 is 1
Code execution
#include<stdio.h> int main() { printf("Judge odd and even numbers:\n"); int num = 12; if ((num & 1) == 0) { printf("%d It's an even number\n",num); } else { printf("%d It's an odd number\n", num); } return 0; }
2. Determine whether the binary bit is 1 or 0 (two methods)
Example: int x = 86// Define an integer variable x and initialize it to 86
Now you need to judge whether the 5th bit is 1 or 0. How to operate?
Method 1 problem solving ideas
As usual, the operation is still performed with the integer 1. Since it is to judge whether the fifth bit of x is 1 or 0, take the integer 1, move 1 to the left by (5 - 1) bits, that is, move 4 bits to the left, then directly perform bit by bit & operation with x, and finally move 4 bits to the right to the first binary bit of the number. If the first bit is 0, the binary number on the fifth bit is 0, otherwise it is 1
Code execution
#include<stdio.h> int main() { int x = 86; printf("Determine whether the 5th binary bit of integer 86 is 1 or 0:\n"); //The use of operators has priority. We don't have to remember this. When there may be ambiguity, we add parentheses, which is both safe and worry-free if ((((1 << 4) & x) >> 4) == 0) { putchar('0'); } else { putchar('1'); } return 0; }
Method 2 problem solving ideas
This method is much simpler than method 1. It uses the problem-solving idea of "judging odd and even numbers". First, move x to the right by (5 - 1) bits, that is, 4 bits to the right, and then phase with 1 &. If the result is 0, the binary number on bit 5 is 0, otherwise it is 1.
Code execution
#include<stdio.h> int main() { int x = 86; printf("Determine whether the 5th binary bit of integer 86 is 1 or 0:\n"); if (((x >> 4) & 1) == 0) { putchar('0'); } else { putchar('1'); } return 0; }
3. Exchange the values of two integer variables (XOR)
Problem solving ideas
Supplement: XOR can be understood as non carry addition, such as 1 + 1 = 0, 0 + 0 = 0, 1 + 0 = 1
XOR: if the binary bits of two numbers are the same, the result is 0, and if they are different, the result is 1
Nature of XOR:
1. Commutative law: the position of the operation factor can be exchanged arbitrarily, and the result remains unchanged;
For example: a ^ b ^ c = b ^ a ^ c;
2. Law of association: i.e. (a ^ b) ^ C = = a ^ (b ^ C);
3. For any number x, there is x ^ x = 0, x ^ 0 = x, which is different from or for 0, and different from or for 0
4. Reflexivity: A ^ B ^ B = A ^ 0 = A, perform exclusive or operation with the same factor continuously, and the final result is yourself
Having said so much, what is the connection between XOR in bit operation and the topic of "exchanging the values of two integer variables"? Please listen to the author's slow way to iron juice
Example: int A = 10, int B = 20, Exchange the values of two variables without introducing the third variable (addition and subtraction can also be used in addition to XOR method, which will be described in detail in zero basis C language later)
Code execution
#include<stdio.h> int main() { int A = 10; int B = 20; printf("Before exchange A = %d B = %d\n", A, B); A = A ^ B; B = A ^ B; A = A ^ B; printf("After exchange A = %d B = %d\n", A, B); return 0; }
4. Find the absolute value of an integer without judgment statements
Problem solving ideas
If you don't understand the above expression, it doesn't matter. The expression has been given. You only need to know that when you find the absolute value of an integer without judgment statement, you can use it.
Code execution
This topic is written in Java language
public class Test10_16 { public static void main(String[] args) { System.out.println("Find the absolute value of an integer without judgment statements"); int num5 = -100; System.out.println("num5 The absolute value of is:" + ((num5 ^ (num5 >> 31)) + (num5 >>> 31))); } }
3, Practical examples
Example 1: how to find the only paired number in the array
1-10 these 10 numbers are placed in the array containing 11 elements. Only one element repeats, and the others only appear once. It is required that each array element can only be accessed once. Please design an algorithm to find it without auxiliary storage space. Can you design an algorithm to implement it?
Problem solving ideas
To calculate this problem, we need to master the nature of XOR. The idea is to define a number x, initialize it to 0, XOR it with 11 numbers in the array, and then XOR with 10 natural numbers 1-10. The final result is that number.
Code execution
#include<stdio.h> int main() { int arr[] = { 1,2,3,2,6,4,7,5,8,9,10 }; int sz = sizeof(arr) / sizeof(arr[0]); int x = 0;//x is initialized to 0 because 0 and any number XOR are itself for (int i = 0; i < sz; i++) { x = x ^ arr[i]; } for (int i = 1; i <= sz - 1; i++) { x = x ^ i; } printf("%d\n", x); return 0; }
Example 2. Find out the number that is left alone
In an array, except for one element, other elements appear twice. Please write a program to find the number that appears only once
Problem solving ideas
This question is simpler than the first one. Just XOR
Code execution
#include<stdio.h> int main() { int arr[] = { 1,1,2,3,3,4,4,5,5 }; int sz = sizeof(arr) / sizeof(arr[0]); int x = 0; for (int i = 0; i < sz; i++) { x = x ^ arr[i]; } printf("%d\n", x); return 0; }
Example 3. Number of 1 in binary
Enter an integer and output the number of 1 in the binary representation of the number
For example, the binary representation of 9 is 00000000 00000000 00000000 00001001, and there are two 1s
Method 1 problem solving ideas
Stupid method, count 1 -- > let 1 move, and the integer will not move. Use 32 cycles, and each time, perform bit-by-bit & operation on the number on the corresponding bit
Code execution
#include<stdio.h> int main() { int num = 9; int count = 0;//For counting for (int i = 0; i < 32; i++) { //We must pay attention to the writing method. Although it is simple, it is easy to make mistakes if ((num & (1 << i)) == (1 << i))-----Pay attention to writing if((num & (1 << i) == 1)I was wrong { count++; } } printf("%d\n", count); return 0; }
Method 2 problem solving ideas
In fact, it is a deformation of method 1. Keep the position of 1 unchanged and keep the integer moving to the right
Code execution
#include<stdio.h> int main() { int num = 9; int count = 0; for (int i = 0; i < 32; i++) { if (((num >> i) & 1) == 1) { count++; } } printf("%d\n", count); return 0; }
Method 3 problem solving ideas
Many skills do not pressure the body. Iron juice people had better master all these three methods, and they are not allowed to use them in future topics.
Using the loop, when the integer becomes 0, the loop ends, and the operation num = (num - 1) & num is executed in the loop body
Maybe you didn't think of this solution at the beginning. So did the author. I was very confused at the beginning, but when you read it, you will have a refreshing feeling, which shows that you understand that it can still be like this. Although we may not have thought of it before, now that we have met it, we should remember it and be able to use it when it appears again in the future. Come on, iron juice.
Code execution
#include<stdio.h> int main() { int num = 9; int count = 0; while (num != 0) { num = (num - 1) & num; count++; } printf("%d\n", count); return 0; }
Example 4. Is it an integer power of 2
The same statement determines whether an integer is an integer power of 2
Problem solving ideas
Judge whether an integer is the integer power of 2, that is, there is only one 1 in the binary of this integer
Code execution
Look, here we use method 3 of the previous question, so should we remember
#include<stdio.h> int main() { int num = 9; if (((num - 1) & num) == 0) { printf("YES\n"); } else { printf("NO\n"); } return 0; }
Example 5: swap parity bits of integers
Note: using 1 to do & operation is actually retention, and using 0 to do & operation is actually elimination
Problem solving ideas
#include<stdio.h> int main() { int num = 9; //0000....00001001 int a = 0xaaaaaaaa; //1010....10101010 int b = 0x55555555; //0101....01010101 int c = num & a; //The purpose is to retain the even bits of num int d = num & b; //The purpose is to retain the odd digits of num printf("%d\n", ((c >> 1) ^ (d << 1))); return 0; }
Thinking questions: K times and once
Title Description: only one number in the array appears once, and other numbers appear K times. Please output the number that appears once. Bit operation is required, and violent solution method cannot be used.
Note: in the future, the author may leave the next thinking question for iron juice in each blog post. When the author publishes this series of blog posts next time, the problem-solving ideas and code execution will be announced, which is the right to review.
4, Blue bridge conclusion: meet blue bridge meet you, not negative code, not negative Qing!
University can be said to be the best stage of life. Although we are under pressure, it is nothing compared with our future work and life. For us in the IT wave, I hope you will live up to your youth, cherish opportunities, enrich experience and make achievements.
5, Author request
Iron juice, the author's blog posts are from the secondary processing of paper and electronic notes. It takes a lot of effort. If I feel that the writing is OK, give me some praise, collect and pay attention. Your support is the greatest driving force of the author