Common Techniques for Bitwise Operations

1. Use or operation | and spaces to convert English characters to lowercase

@Test
public void test() {
    
    
    System.out.println(('a' | ' ') == 'a');//true
    System.out.println(('A' | ' ') == 'a');//true
}

2. Use AND operation & and underscore to convert English characters to uppercase

@Test
public void test02(){
    
    
    System.out.println(('b' & '_') == 'B');//true
    System.out.println(('B' & '_') == 'B');//true
}

3. Use the XOR operation ^ and spaces to swap the upper and lower case of English characters

@Test
public void test03(){
    
    
    System.out.println(('d' ^ ' ') == 'D');//true
    System.out.println(('D' ^ ' ') == 'd');//true
}

4. Determine whether two numbers have different signs

@Test
public void test04(){
    
    
    int x = -1, y = 2;
    boolean f = ((x ^ y) < 0); // true

    int xx = 3, yy = 2;
    boolean flag = ((xx ^ yy) < 0); // false
}

5. Swap two numbers without using a temporary variable

@Test
public void test05() {
    
    
    int a = 1, b = 2;
    a ^= b;
    b ^= a;
    a ^= b;
    System.out.println("a="+a+",b="+b);
    // 现在 a = 2, b = 1
}

6. Algorithm common operations

n&(n-1) This operation is common in algorithms, and its function is to eliminate the last 1 in the binary representation of the number n.
insert image description here

Its core logic is that n - 1 can definitely eliminate the last 1, and at the same time turn all subsequent 0s into 1s, and then do an & operation with n to only change the last 1 into 0.

7. Determine whether a number is an exponent of 2

If a number is an exponent of 2, its binary representation must contain only one 1:

2^0 = 1 = 0b0001
2^1 = 2 = 0b0010
2^2 = 4 = 0b0100

It is very simple if you use the bitwise operation technique (note the operator precedence, parentheses cannot be omitted):

public boolean isPowerOfTwo(int n) {
    
    
    if (n < 0) {
    
    
        return false;
    }
    return (n & (n - 1)) == 0;
}

8. Find elements that occur only once

The result of XOR operation between a number and itself is 0, that is, a ^ a = 0; the result of XOR operation between a number and 0 is itself, that is, a ^ 0 = a.

In this regard, we only need to XOR all the numbers, and the paired numbers will become 0, and the XOR of the single number and 0 is still itself, so the final XOR result is an element that only appears once:

public int singleNumber(int[] arr) {
    
    

    int result = 0;
    for (int data : arr) {
    
    
        result ^= data;
    }
    return result;
}

————————————————
Copyright statement: This article is the original article of CSDN blogger "Slow is [fast]", following the CC 4.0 BY-SA copyright agreement, please attach the original source for reprinting link and this statement.
Original link: https://blog.csdn.net/u012068483/article/details/108222415

Guess you like

Origin blog.csdn.net/weixin_44153131/article/details/128390939