Bit manipulations

  1. Multiply two Numbers Without Using * Operator
m=0;
          while (a)
          {
                if (a&1)
                   m+=b;
                a>>=1;
                b<<=1;
          }
          return m;
  1. check number is even or odd

    http://www.programmingsimplified.com/c/source-code/c-program-check-odd-even

  2. check if a num is power of 2

     public class Solution {
     public boolean isPowerOfTwo(int n) {
         if(n<=0) 
         return false;
    
         while(n>2){
             int t = n>>1;
             int c = t<<1;
    
             if(n-c != 0)
                 return false;
    
             n = n>>1;
         }
    
         return true;
     }
    }
    

    solution II:

     public class Solution {
     public boolean isPowerOfTwo(int n) {
         if(n<=0) 
             return false;
         return ((n & n-1) == 0);
     }
    }
    
  3. check a number is positive or negative

    int k = (a >> 31) & 1; k == 1 negative, k == 0 positive

  4. find max of two numbers without comparison

    check Cracking coding interview at page 476

int findMax( int x, int y)
{
   int z = x - y;
   int i  = (z  >>  31)  &  0x1;
   int  max  =  x - i  *  z;
   return max;
}