# Category Archives: Bit operation

## Gray Code

The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must … Continue reading

Posted in Bit operation, Dynamic programming | Leave a comment

## Divide Two Integers

Divide two integers without using multiplication, division and mod operator. C++: 01 int divide(int dividend, int divisor) { 02         assert(divisor!=0); 03         if(dividend==0) 04             return 0; 05         int … Continue reading

Posted in Bit operation, Number trick | Leave a comment

## Fun with Bit Operations

What does the following function mystery() do? bool mystery(unsigned int x) {   return !(x & (x-1)); } It will return true if x is power of 2.

Posted in Bit operation | Leave a comment

## Reverse bits

Reverse bits of an unsigned integer. C++: 1 unsigned int reverseInt(unsigned int a) 2 { 3     int size=sizeof(unsigned int)*8; 4     for(int i=0;i<size/2;i++){ 5         if((a&(1<<i))^(a&(1<<(size–1–i)))) 6             a^=(1<<i)|(1<<(size–1–i)); 7     } 8     return … Continue reading

Posted in Bit operation | Leave a comment

## Add two numbers with out use +

Write a function that adds two numbers. You should not use + or any arithmetic operations. C++: 01 int addwithoutplus(int a, int b) 02 { 03     if(a==0) 04         return b; 05     if(b==0) 06         return … Continue reading

Posted in Bit operation, Number trick | Leave a comment

## Position of rightmost set bit

Write a one line C function to return position of first 1 from right to left, in binary representation of an Integer. I/P    18,   Binary Representation 010010 O/P   2 I/P    19,   Binary Representation 010011 O/P … Continue reading

Posted in Bit operation | Leave a comment

## Count the number of 1 in binary representation.

Count the number of 1 in binary representation. C++: 1 int countOne(int x) 2 { 3     int cnt=0; 4     while(x){ 5         cnt++; 6         x=x&(x–1); 7     } 8     return cnt; 9 }

Posted in Bit operation | Leave a comment