Bit Manipulation

Copyright © 直通硅谷

http://www.zhitongguigu.com/

Decimal= 1                   0

          1*10^   +           0*10^0

Binary=     0000 1         0               1            0

                         1*2^3      0*2^2    1*2^1    0*2^0

                           8  +           0 +           2 +        0      =10

10------->   binary representation of 10

Binary =   0000 1         0                     1                0

             1*2^3  +   0*2^2   +   1*2^1   +   0*2^0  /1

                       8   +         0   +                2   +          0            =10

 

10/2==5...... 10%2==0   ------>least significant bit

5/2  ==2...... 5%2  ==1

2/2  ==1...... 2%2  ==0

1/2  ==0...... 1%2  ==1   ------>most significant bit

1010

1 Byte= 8 bits   can represent 0 to 256 - 1 == 2^8 - 1

32 bit machine

int a = 10;            // signed

0000 0000 0000 0000      0000 0000 0000 1010

0: positive

1: negative

How do we represent a negative number, and what is the relationship between the positive representation

1 vs  -1;

对于负数 "-1" :  1 变反加1

1 == 0000 0000 0000 0000 0000 0000 0000 0001

变反 1111 1111 1111 1111 1111 1111 1111 11110

加一 1111 1111 1111 1111 1111 1111 1111 1111

Sixty types of operations in bit level:

  •  & AND (&&)​​

    11001110  

&  10011000

=  10001000

  • |      OR
  • ~      NOT (1->0 AND 0>1 FOR EACH BIT) 

              a =  10  => ~a  =>

Copyright © 直通硅谷

http://www.zhitongguigu.com/

  • ^XOR

00->0

11->0

01 or 10 ->1

  • << left shift
  • >>right shift (positive number):

​e.g. int x= 1; x>>1,将x向右移动一位,左侧补充零

if the variable ch contains the bit pattern 01100101,

then ch>>1 will give the output as   0011100101, and ch>>2 will give 00011100101.

 

Copyright © 直通硅谷

http://www.zhitongguigu.com/

Given a number x, how to set x's k-th bit to 1?

e.g. x == 0000 0000, and k =4;

Copyright © 直通硅谷

http://www.zhitongguigu.com/

Given a number x, how to set x's k-th bit to 1?

e.g. x == 0000 0000, and k =4;

Step 1: int temp = 1;

Step 2: temp = temp << (k-1);

Step 3: x = x \ temp;

for short:  x\= temp;

 

Copyright © 直通硅谷

http://www.zhitongguigu.com/

 

Given a number, how to set a's k-th bit to 0?

e.g. a == xxx0 xxxxx, and k = 5;

 

Copyright © 直通硅谷

http://www.zhitongguigu.com/


Given a number, how to set a's k-th bit to 0?

e.g. a == xxx0 xxxxx, and k = 5;

Step 1: int temp = 1;

Step 2: temp = temp <<(k-1);        0001 0000

Step 3: temp = ~temp;                   1110 1111

Step 4: a = a & temp;  for short a &= temp;

Copyright © 直通硅谷

http://www.zhitongguigu.com/

 Determine whether a number x is a power of 2  (x == 2^n)

 

Copyright © 直通硅谷

http://www.zhitongguigu.com/

 Determine whether a number x is a power of 2  (x == 2^n)

 

x*2^n +y*2(n-1) + ......

converted to how to check whether there is only one digit  in the binary representation of the number is 1.

public bool check(int num){
    int count = 0;
    while(num > 0) {
        if((num & 1) == 1){
            count++;
        }
        num = num >> 1;
    }
    return count == 1;
}

Copyright © 直通硅谷

http://www.zhitongguigu.com/

Method 2:

 

Assume x is a positive number, then this method works.

What if x can be 0?

return ((x & ( x - 1 )) == 0  && x ! = 0);

e.g 00000000000000 1 000000000

      00000000000000 0 111111111

Question

Copyright © 直通硅谷

http://www.zhitongguigu.com/

How to determine the number of bits that are different between two positive integers?

 

a = 0101

b = 0110

_________

c = 0011

 

Copyright © 直通硅谷

http://www.zhitongguigu.com/

public int CheckDiffNum(int a, int b){
    int count = 0;
    for(int c = a ^ b; c != 0; c >>= 1) {
        count += c & 1;
    }
    return count;
}

Copyright © 直通硅谷

http://www.zhitongguigu.com/

Question 

 What happens if we assign a negative number to an unsigned integer?

Copyright © 直通硅谷

http://www.zhitongguigu.com/

Question 

 What happens if we assign a negative number to an unsigned integer?

unsigned int a;

a = b; // b = -1, 1111 1111 1111...

Principle

When assigning a negative number to an unsigned integer, the binary representation DOES NOT change.

While we will calculate the value of the unsigned integer by using the current binary representation.

 

single number

Given an array of integers, every element appears twice except for one. Find that single one.

public class Solution {
	public int singleNumber(int[] A) {

		// initiate a map which is from index to number
		HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

		// the for loop cost O(n).
		for (int i = 0; i < A.length; i++) {
			int index = 0;
			int number = 0;

			number = A[i];
			if (map.containsKey(number)) {
				index = map.get(number);
				++index;
			} else {
				++index;
			}
			map.put(number, index);
		}
		int solution = 0;
		for (int j = 0; j < A.length; j++){
			if(map.get(A[j]) == 1){
				 solution = A[j];
			}
		}
		return solution;
	}

}
public class Solution {
	public int singleNumber(int[] A) {
		int num=0;
                for(int x : A) num ^= x;
                return num;
	}

}

single number 2

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.

single number 2

public int singleNumber(int[] nums) {
    int ans = 0;
    for(int i = 0; i < 32; i++) {
        int sum = 0;
        for(int j = 0; j < nums.length; j++) {
            if(((nums[j] >> i) & 1) == 1) {
                sum++;
                sum %= 3;
            }
        }
        if(sum != 0) {
            ans |= sum << i;
        }
    }
    return ans;
}

single number 3

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

single number 3

public class Solution {
    public int[] singleNumber(int[] nums) {
        // Pass 1 : 
        // Get the XOR of the two numbers we need to find
        int diff = 0;
        for (int num : nums) {
            diff ^= num;
        }
        // Get its last set bit
        diff &= -diff;
        
        // Pass 2 :
        int[] rets = {0, 0}; // this array stores the two numbers we will return
        for (int num : nums)
        {
            if ((num & diff) == 0) // the bit is not set
            {
                rets[0] ^= num;
            }
            else // the bit is set
            {
                rets[1] ^= num;
            }
        }
        return rets;
    }
}

Copyright © 直通硅谷

http://www.zhitongguigu.com/

Homework

Made with Slides.com