Bit Maipulation Algorithms
Bit Maipulation Algorithms
Given a number having only one 1 and all other 0s in its binary representation, fnd position of the only set bit.
Source: Microsoft Interview | 18
The idea is to start from rightmost bit and one by one check value of every bit. Following is detailed algorithm.
1) If number is power of two then and then only its binary representation contains only one 1 . Thats why check
whether given number is power of 2 or not. If given number is not power of 2, then print error message and exit.
2) Initialize two variables; i = 1 (for looping) and pos = 1 (to fnd position of set bit)
3) Inside loop, do bitwise AND of i and number N. If value of this operation is true, then pos bit is set, so
break the loop and return position. Otherwise, increment pos by 1 and left shift i by 1 and repeat the
procedure.
{
// Unset current bit and set the next bit in 'i'
i = i << 1;
// increment position
++pos;
}
return pos;
}
// Driver program to test above function
int main(void)
{
int n = 16;
int pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid number\n", n):
printf("n = %d, Position %d \n", n, pos);
n = 12;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid number\n", n):
printf("n = %d, Position %d \n", n, pos);
n = 128;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid number\n", n):
printf("n = %d, Position %d \n", n, pos);
return 0;
}
Output:
n = 16, Position 5
n = 12, Invalid number
n = 128, Position 8
Following is another method for this problem. The idea is to one by one right shift the set bit of given number
n until n becomes 0. Count how many times we shifted to make n zero. The fnal count is position of the set
bit.
int n = 0;
int pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid number\n", n):
printf("n = %d, Position %d \n", n, pos);
n = 12;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid number\n", n):
printf("n = %d, Position %d \n", n, pos);
n = 128;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid number\n", n):
printf("n = %d, Position %d \n", n, pos);
return 0;
}
Output:
n = 0, Invalid number
n = 12, Invalid number
n = 128, Position 8
We can also use log base 2 to find the position. Thanks to Arunkumar for suggesting this solution.
#include <stdio.h>
unsigned int Log2n(unsigned int n)
{
return (n > 1)? 1 + Log2n(n/2): 0;
}
int isPowerOfTwo(unsigned n)
{
return n && (! (n & (n-1)) );
}
int findPosition(unsigned n)
{
if (!isPowerOfTwo(n))
return -1;
return Log2n(n) + 1;
}
// Driver program to test above function
int main(void)
{
int n = 0;
int pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid number\n", n):
printf("n = %d, Position %d \n", n, pos);
n = 12;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid number\n", n):
printf("n = %d, Position %d \n", n, pos);
n = 128;
pos = findPosition(n);
(pos == -1)? printf("n = %d, Invalid number\n", n):
printf("n = %d, Position %d \n", n, pos);
return 0;
}
Output:
n = 0, Invalid number
n = 12, Invalid number
n = 128, Position 8
March 6, 2013
Given an unsigned integer, swap all odd bits with even bits. For example, if the given number is 23 (00010111),
it should be converted to 43 (00101011). Every even position bit is swapped with adjacent bit on right side
(even position bits are highlighted in binary representation of 23), and every odd position bit is swapped with
adjacent on left side.
If we take a closer look at the example, we can observe that we basically need to right shift (>>) all even bits (In
the above example, even bits of 23 are highlighted) by 1 so that they become odd bits (highlighted in 43), and
left shift (<<) all odd bits by 1 so that they become even bits. The following solution is based on this
observation. The solution assumes that input number is stored using 32 bits.
Let the input number be x
1) Get all even bits of x by doing bitwise and of x with 0xAAAAAAAA. The number 0xAAAAAAAA is a 32 bit
number with all even bits set as 1 and all odd bits as 0.
2) Get all odd bits of x by doing bitwise and of x with 0x55555555. The number 0x55555555 is a 32 bit number
with all odd bits set as 1 and all even bits as 0.
3) Right shift all even bits.
4) Left shift all odd bits.
5) Combine new even and odd bits and return.
= x & 055555555;
even_bits >>= 1;
odd_bits <<= 1;
43
Given two bit sequences as strings, write a function to return the addition of the two sequences. Bit strings can
be of diferent lengths also. For example, if string 1 is 1100011 and second string 2 is 10 , then the function
should return 1100101.
Since sizes of two strings may be diferent, we frst make the size of smaller string equal to that of bigger string
by adding leading 0s. After making sizes same, we one by one add bits from rightmost bit to leftmost bit. In
every iteration, we need to sum 3 bits: 2 bits of 2 given strings and carry. The sum bit will be 1 if, either all of the
3 bits are set or one of them is set. So we can do XOR of all bits to fnd the sum bit. How to fnd carry carry
will be 1 if any of the two bits is set. So we can fnd carry by taking OR of all pairs. Following is step by step
algorithm.
1. Make them equal sized by adding 0s at the begining of smaller string.
2. Perform bit addition
..Boolean expression for adding 3 bits a, b, c
..Sum = a XOR b XOR c
..Carry = (a AND b) OR ( b AND c ) OR ( c AND a )
Following is C++ implementation of the above algorithm.
#include <iostream>
using namespace std;
//adds the two bit strings and return the result
string addBitStrings( string first, string second );
// Helper method: given two unequal sized bit strings, converts them to
// same length by aadding leading 0s in the smaller string. Returns the
// the new length
int makeEqualLength(string &str1, string &str2)
{
int len1 = str1.size();
int len2 = str2.size();
if (len1 < len2)
{
for (int i = 0 ; i < len2 - len1 ; i++)
str1 = '0' + str1;
return len2;
}
else if (len1 > len2)
{
for (int i = 0 ; i < len1 - len2 ; i++)
str2 = '0' + str2;
}
return len1; // If len1 >= len2
}
// The main function that adds two bit sequences and returns the addition
string addBitStrings( string first, string second )
{
string result;
// Initialize carry
Sum is 1100101
Write a modifed strcmp function which ignores cases and returns -1 if s1 < s2, 0 if s1 = s2, else returns 1. For
example, your strcmp should consider "GeeksforGeeks" and "geeksforgeeks" as same string.
Source: Microsoft Interview Set 5
Following solution assumes that characters are represented using ASCII representation, i.e., codes for a, b,
c, z are 97, 98, 99, 122 respectively. And codes for A, B, C, Z are 65, 66, 95 respectively.
Following are the detailed steps.
1) Iterate through every character of both strings and do following for each character.
a) If str1[i] is same as str2[i], then continue.
b) If inverting the 6th least signifcant bit of str1[i] makes it same as str2[i], then continue. For example, if
str1[i] is 65, then inverting the 6th bit will make it 97. And if str1[i] is 97, then inverting the 6th bit will make it 65.
c) If any of the above two conditions is not true, then break.
2) Compare the last (or frst mismatching in case of not same) characters.
#include <stdio.h>
/* implementation of strcmp that ingnores cases */
int ic_strcmp(char *s1, char *s2)
{
int i;
for (i = 0; s1[i] && s2[i]; ++i)
{
/* If characters are same or inverting the 6th bit makes them same */
if (s1[i] == s2[i] || (s1[i] ^ 32) == s2[i])
continue;
else
break;
}
/* Compare the last (or first mismatching in case of not same) characters */
if (s1[i] == s2[i])
return 0;
if ((s1[i]|32) < (s2[i]|32)) //Set the 6th bit in both, then compare
return -1;
return 1;
}
// Driver program to test above function
int main(void)
{
printf("ret:
printf("ret:
printf("ret:
printf("ret:
printf("ret:
printf("ret:
return 0;
%d\n",
%d\n",
%d\n",
%d\n",
%d\n",
%d\n",
ic_strcmp("Geeks", "apple"));
ic_strcmp("", "ABCD"));
ic_strcmp("ABCD", "z"));
ic_strcmp("ABCD", "abcdEghe"));
ic_strcmp("GeeksForGeeks", "gEEksFORGeEKs"));
ic_strcmp("GeeksForGeeks", "geeksForGeeks"));
Output:
ret: 1
ret: -1
ret: -1
ret: -1
ret: 0
ret: 0
1) Let us take number 'NUM' and we want to check whether it's 0th bit is
ON or OFF
bit = 2 ^ 0 (0th bit)
if
NUM & bit == 1 means 0th bit is ON else 0th bit is OFF
Let us take unsigned integer (32 bit), which consist of 0-31 bits. To print binary representation of unsigned
integer, start from 31th bit, check whether 31th bit is ON or OFF, if it is ON print 1 else print 0 . Now check
whether 30th bit is ON or OFF, if it is ON print 1 else print 0 , do this for all bits from 31 to 0, fnally we will get
binary representation of number.
void bin(unsigned n)
{
unsigned i;
for (i = 1 << 31; i > 0; i = i / 2)
(n & i)? printf("1"): printf("0");
}
int main(void)
{
bin(7);
printf("\n");
bin(4);
}
Method 2: Recursive
Following is recursive method to print binary representation of NUM.
void bin(unsigned n)
{
/* step 1 */
if (n > 1)
bin(n/2);
/* step 2 */
printf("%d", n % 2);
}
int main(void)
{
bin(7);
printf("\n");
bin(4);
}
October 3, 2012
Given an array where every element occurs three times, except one element which occurs only once. Find the
element that occurs once. Expected time complexity is O(n) and O(1) extra space.
Examples:
#include <stdio.h>
int getSingle(int arr[], int n)
{
int ones = 0, twos = 0 ;
int common_bit_mask;
// Let us take the example of {3, 3, 2, 3} to understand this
for( int i=0; i< n; i++ )
{
/* The expression "one & arr[i]" gives the bits that are
there in both 'ones' and new element from arr[].
We
/* XOR the new bits with previous 'ones' to get all bits
appearing odd number of times
Value of 'ones' will be set as 3, 0, 2 and 3 after 1st,
2nd, 3rd and 4th iterations respectively */
ones
= ones ^ arr[i];
/* The common bits are those bits which appear third time
So these bits should not be there in both 'ones' and 'twos'.
common_bit_mask contains all these bits as 0, so that the bits
can
be removed from 'ones' and 'twos'
Value of 'common_bit_mask' will be set as 00, 00, 01 and 10
after 1st, 2nd, 3rd and 4th iterations respectively */
common_bit_mask = ~(ones & twos);
/* Remove common bits (the bits that appear third time) from
'ones'
Value of 'ones' will be set as 3, 0, 0 and 2 after 1st,
2nd, 3rd and 4th iterations respectively */
ones &= common_bit_mask;
/* Remove common bits (the bits that appear third time) from
'twos'
Value of 'twos' will be set as 0, 3, 1 and 0 after 1st,
2nd, 3rd and 4th itearations respectively */
twos &= common_bit_mask;
// uncomment this code to see intermediate values
//printf (" %d %d \n", ones, twos);
}
return ones;
}
int main()
{
int arr[] = {3, 3, 2, 3};
int n = sizeof(arr) / sizeof(arr[0]);
printf("The element with single occurrence is %d ",
getSingle(arr, n));
return 0;
}
Output:
#include <stdio.h>
#define INT_SIZE 32
int getSingle(int arr[], int n)
{
// Initialize result
int result = 0;
int x, sum;
// Iterate through every bit
for (int i = 0; i < INT_SIZE; i++)
{
// Find sum of set bits at ith position in all
// array elements
sum = 0;
x = (1 << i);
for (int j=0; j< n; j++ )
{
if (arr[j] & x)
sum++;
}
Given two signed integers, write a function that returns true if the signs of given integers are diferent, otherwise
false. For example, the function should return true -1 and +100, and should return false for -100 and -200. The
function should not use any of the arithmetic operators.
Let the given integers be x and y. The sign bit is 1 in negative numbers, and 0 in positive numbers. The XOR of
x and y will have the sign bit as 1 if they have opposite sign. In other words, XOR of x and y will be negative
number number if x and y have opposite signs. The following code use this logic.
#include<stdbool.h>
#include<stdio.h>
bool oppositeSigns(int x, int y)
{
}
The function is written only for compilers where size of an integer is 32 bit. The expression basically checks
sign of (x^y) using bitwise operator >>. As mentioned above, the sign bit for negative numbers is always 1. The
sign bit is the leftmost bit in binary representation. So we need to checks whether the 32th bit (or leftmost bit) of
x^y is 1 or not. We do it by right shifting the value of x^y by 31, so that the sign bit becomes the least signifcant
bit. If sign bit is 1, then the value of (x^y)>>31 will be 1, otherwise 0
Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n.
Examples:
Input: n = 3
Output:
Input: n = 6
Output: 9
Input: n = 7
Output: 12
Input: n = 8
Output: 13
Source: Amazon Interview Question
Method 1 (Simple)
A simple solution is to run a loop from 1 to n and sum the count of set bits in all numbers from 1 to n.
Method 2 (Tricky)
If the input number is of the form 2^b -1 e.g., 1,3,7,15.. etc, the number of set bits is b * 2^(b-1). This is
because for all the numbers 0 to (2^b)-1, if you complement and flip the list you end up with the same list (half
the bits are on, half of).
If the number does not have all set bits, then some position m is the position of leftmost set bit. The number of
set bits in that position is n (1 << m) + 1. The remaining set bits are in two parts:
1) The bits in the (m-1) positions down to the point where the leftmost bit becomes 0, and
2) The 2^(m-1) numbers below that point, which is the closed form above.
An easy way to look at it is to consider the number 6:
0|0 0
0|0 1
0|1 0
0|1 1
-|
1|0 0
1|0 1
1|1 0
The leftmost set bit is in position 2 (positions are considered starting from 0). If we mask that of what remains
is 2 (the "1 0" in the right part of the last row.) So the number of bits in the 2nd position (the lower left box) is 3
(that is, 2 + 1). The set bits from 0-3 (the upper right box above) is 2*2^(2-1) = 4. The box in the lower right is
the remaining bits we haven't yet counted, and is the number of set bits for all the numbers up to 2 (the value of
the last entry in the lower right box) which can be fgured recursively.
{
int m = 0;
while (n
> 1)
{
n = n >> 1;
m++;
}
return m;
}
/* Given the position of previous leftmost set bit in n (or an upper
bound on leftmost position) returns the new position of leftmost
set bit in n
*/
< temp)
{
temp = temp >> 1;
m--;
}
return m;
}
// The main recursive function used by countSetBits()
unsigned int _countSetBits(unsigned int n, int m);
// Returns count of set bits present in all numbers from 1 to n
unsigned int countSetBits(unsigned int n)
{
// Get the position of leftmost set bit in n. This will be
// used as an upper bound for next set bit function
int m = getLeftmostBit (n);
// Use the position
return _countSetBits (n, m);
}
unsigned int _countSetBits(unsigned int n, int m)
{
// Base Case: if n is 0, then set bit count is 0
if (n == 0)
return 0;
/* get position of next leftmost set bit */
m = getNextLeftmostBit(n, m);
// If n is of the form 2^x-1, i.e., if n is like 1, 3, 7, 15, 31,..
etc,
// then we are done.
// Since positions are considered starting from 0, 1 is added to m
if (n == ((unsigned int)1<<(m+1))-1)
return (unsigned int)(m+1)*(1<<m);
// update n for next recursive call
n = n - (1<<m);
return (n+1) + countSetBits(n) + m*(1<<(m-1));
}
// Driver program to test above functions
int main()
{
int n = 17;
printf ("Total set bit count is %d", countSetBits(n));
return 0;
}
Total set bit count is 35
Time Complexity: O(Logn). From the frst look at the implementation, time complexity looks more. But if we take
a closer look, statements inside while loop of getNextLeftmostBit() are executed for all 0 bits in n. And the
number of times recursion is executed is less than or equal to set bits in n. In other words, if the control goes
inside while loop of getNextLeftmostBit(), then it skips those many bits in recursion.
Given a number x and two positions (from right side) in binary representation of x, write a function that swaps n
bits at given two positions and returns the result. It is also given that the two sets of bits do not overlap.
Examples:
Example 2
Input:
x = 28 (11100)
p1 = 0 (Start from first bit from right side)
p2 = 3 (Start from 4th bit from right side)
n = 2 (No of bits to be swapped)
Output:
7 (00111)
The 2 bits starting from 0th postion (from right side) are
swapped with 2 bits starting from 4th position (from right side)
Solution
We need to swap two sets of bits. XOR can be used in a similar way as it is used to swap 2 numbers. Following
is the algorithm.
Output:
Result = 7
Following is a shorter implementation of the same logic
int swapBits(unsigned int x, unsigned int p1, unsigned int p2, unsigned int n)
{
/* xor contains xor of two sets */
unsigned int xor = ((x >> p1) ^ (x >> p2)) & ((1U << n) - 1);
/* To swap two sets, we need to again XOR the xor with original sets */
return x ^ ((xor << p1) | (xor << p2));
}
Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic
operators (+, ++, , -, .. etc).
Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing
AND (&) of two bits.
Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers. If x
and y dont have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To
incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We
calculate (x & y) << 1 and add it to x ^ y to get the required result.
#include<stdio.h>
int Add(int x, int y)
{
// Iterate till there is no carry
while (y != 0)
{
// carry now contains common set bits of x and y
int carry = x & y;
Write a C program to fnd the smallest of three integers, without using any of the comparison operators.
Let 3 input numbers be x, y and z.
#include<stdio.h>
int smallest(int x, int y, int z)
{
int c = 0;
while ( x && y && z )
{
x--;
}
return c;
}
int main()
{
int x = 12, y = 15, z = 5;
printf("Minimum of 3 numbers is %d", smallest(x, y, z));
return 0;
}
This methid doesnt work for negative numbers. Method 2 works for negative nnumbers also.
}
/* Function to find minimum of 3 numbers x, y and z*/
int smallest(int x, int y, int z)
{
return min(x, min(y, z));
}
int main()
{
int x = 12, y = 15, z = 5;
printf("Minimum of 3 numbers is %d", smallest(x, y, z));
return 0;
}
There are several ways we can do it as we are sure that always one Zero is there. Thanks to devendraiiit for
suggesting following 3 methods.
Method 1
Method 4
Thanks to purvi for suggesting this method.
Given an integer array of length N (an arbitrarily large number). How to count number of set bits in the array?
The simple approach would be, create an efficient method to count set bits in a word (most prominent size,
usually equal to bit length of processor), and add bits from individual elements of array.
Various methods of counting set bits of an integer exists, see this for example. These methods run at best
O(logN) where N is number of bits. Note that on a processor N is fxed, count can be done in O(1) time on 32
bit machine irrespective of total set bits. Overall, the bits in array can be computed in O(n) time, where n is
array size.
However, a table look up will be more efficient method when array size is large. Storing table look up that can
handle 232 integers will be impractical.
The following code illustrates simple program to count set bits in a randomly generated 64 K integer array. The
idea is to generate a look up for frst 256 numbers (one byte), and break every element of array at byte
boundary. A meta program using C/C++ preprocessor generates the look up table for counting set bits in a
byte.
The mathematical derivation behind meta program is evident from the following table (Add the column and row
indices to get the number, then look into the table to get set bits in that number. For example, to get set bits in
10, it can be extracted from row named as 8 and column named as 2),
0, 1, 2, 3
0 - 0, 1, 1, 2 -------- GROUP_A(0)
4 - 1, 2, 2, 3 -------- GROUP_A(1)
8 - 1, 2, 2, 3 -------- GROUP_A(1)
12 - 2, 3, 3, 4 -------- GROUP_A(2)
16 - 1, 2, 2, 3 -------- GROUP_A(1)
20 - 2, 3, 3, 4 -------- GROUP_A(2)
24 - 2, 3, 3, 4 -------- GROUP_A(2)
28 - 3, 4, 4, 5 -------- GROUP_A(3) ... so on
From the table, there is a patten emerging in multiples of 4, both in the table as well as in the group parameter.
The sequence can be generalized as shown in the code.
Complexity:
All the operations takes O(1) except iterating over the array. The time complexity is O(n) where n is size of
array. Space complexity depends on the meta program that generates look up.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/* Size of array 64 K */
#define SIZE (1 << 16)
/* Meta program that generates set bit count
array of first 256 integers */
/* GROUP_A - When combined with META_LOOK_UP
generates count for 4x4 elements */
#define GROUP_A(x) x, x + 1, x + 1, x + 2
/* GROUP_B - When combined with META_LOOK_UP
generates count for 4x4x4 elements */
#define GROUP_B(x) GROUP_A(x), GROUP_A(x+1), GROUP_A(x+1), GROUP_A(x+2)
/* GROUP_C - When combined with META_LOOK_UP
generates count for 4x4x4x4 elements */
#define GROUP_C(x) GROUP_B(x), GROUP_B(x+1), GROUP_B(x+1), GROUP_B(x+2)
/* Provide appropriate letter to generate the table */
#define META_LOOK_UP(PARAMETER) \
GROUP_##PARAMETER(0), \
GROUP_##PARAMETER(1), \
GROUP_##PARAMETER(1), \
GROUP_##PARAMETER(2)
\
}
return count;
}
/* Driver program, generates table of random 64 K numbers */
int main()
{
int index;
int random[SIZE];
/* Seed to the random-number generator */
srand((unsigned)time(0));
/* Generate random numbers. */
for( index = 0; index < SIZE; index++ )
{
random[index] = rand();
}
printf("Total number of bits = %d\n", countSetBits(random, SIZE));
return 0;
}
Given a number x, fnd next number with same number of 1 bits in its binary representation.
For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit
machine). It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (10001 2).
Algorithm:
When we observe the binary sequence from 0 to 2 n 1 (n is # of bits), right most bits (least signifcant) vary
rapidly than left most bits. The idea is to fnd right most string of 1s in x, and shift the pattern to right extreme,
except the left most bit in the pattern. Shift the left most bit in the pattern (omitted bit) to left part of x by one
position. An example makes it more clear,
x = 156
10
x = 10011100
(2)
10011100
00011100 - right most string of 1's in x
00000011 - right shifted pattern except left most bit ------> [A]
00010000 - isolated left most bit of right most 1's pattern
00100000 - shiftleft-ed the isolated bit by one position ------> [B]
10000000 - left part of x, excluding right most 1's pattern ------> [C]
10100000 - add B and C (OR operation) ------> [D]
10100011 - add A and D which is required number 163
(10)
After practicing with few examples, it easy to understand. Use the below given program for generating more
sets.
Program Design:
We need to note few facts of binary numbers. The expression x & -x will isolate right most set bit in x (ensuring
x will use 2s complement form for negative numbers). If we add the result to x, right most string of 1 s in x will
be reset, and the immediate 0 left to this pattern of 1s will be set, which is part [B] of above explanation. For
example if x = 156, x & -x will result in 00000100, adding this result to x yields 10100000 (see part D). We left
with the right shifting part of pattern of 1s (part A of above explanation).
There are diferent ways to achieve part A. Right shifting is essentially a division operation. What should be our
divisor? Clearly, it should be multiple of 2 (avoids 0.5 error in right shifting), and it should shift the right most 1 s
pattern to right extreme. The expression (x & -x) will serve the purpose of divisor. An EX-OR operation between
the number X and expression which is used to reset right most bits, will isolate the rightmost 1 s pattern.
A Correction Factor:
Note that we are adding right most set bit to the bit pattern. The addition operation causes a shift in the bit
positions. The weight of binary system is 2, one shift causes an increase by a factor of 2. Since the increased
number (rightOnesPattern in the code) being used twice, the error propagates twice. The error needs to be
corrected. A right shift by 2 positions will correct the result.
The popular name for this program is same number of one bits.
#include<iostream>
using namespace std;
typedef unsigned int uint_t;
// this function returns next higher number with same number of set bits as x.
uint_t snoob(uint_t x)
{
uint_t rightOne;
uint_t nextHigherOneBit;
uint_t rightOnesPattern;
uint_t next = 0;
if(x)
{
// right most set bit
rightOne = x & -(signed)x;
// reset the pattern and set next higher bit
// left part of x will be here
nextHigherOneBit = x + rightOne;
// nextHigherOneBit is now part [D] of the above explanation.
// isolate the pattern
rightOnesPattern = x ^ nextHigherOneBit;
// right adjust pattern
rightOnesPattern = (rightOnesPattern)/rightOne;
// correction factor
rightOnesPattern >>= 2;
// rightOnesPattern is now part [A] of the above explanation.
// integrate new pattern (Add [D] and [A])
next = nextHigherOneBit | rightOnesPattern;
}
return next;
}
int main()
{
int x = 156;
cout<<"Next higher number with same number of set bits is "<<snoob(x);
getchar();
return 0;
}
Note those zeros in red color, they contribute to remainder in division operation. We can get mask for those
zeros by decrementing the divisor by 1.
Generalizing the above pattern, a number that can be written in 2 n form will have only one bit set followed by n
zeros on the right side of 1. When a number (N) divided by (2 n), the bit positions corresponding to the above
mentioned zeros will contribute to the remainder of division operation. An example can make it clear,
Write a program to add one to a given number. You are not allowed to use operators like +, -, *, /, ++,
etc.
Examples:
Input: 12
Output: 13
Input: 6
Output: 7
Yes, you guessed it right, we can use bitwise operators to achieve this. Following are diferent methods to
achieve same using bitwise operators.
Method 1
To add 1 to a number x (say 0011000111), we need to flip all the bits after the rightmost 0 bit (we get
0011000000). Finally, flip the rightmost 0 bit also (we get 0011001000) and we are done.
#include<stdio.h>
int addOne(int x)
{
int m = 1;
/* Flip all the set bits until we find a 0 */
while( x & m )
{
x = x^m;
m <<= 1;
}
/* flip the rightmost 0 bit */
x = x^m;
return x;
}
int addOne(int x)
{
return (-(~x));
}
/* Driver program to test above functions*/
int main()
{
printf("%d", addOne(13));
getchar();
return 0;
}
Example, assume the machine word length is one *nibble* for simplicity.
And x = 2 (0010),
~x = ~2 = 1101 (13 numerical)
-~x = -1101
Interpreting bits 1101 in 2s complement form yields numerical value as -(2^4 13) = -3. Applying - on the
result leaves 3. Same analogy holds for decrement. See this comment for implementation of decrement.
Note that this method works only if the numbers are stored in 2 s complement form.
Given a integer x, write a function that multiplies x with 3.5 and returns the integer result. You are not allowed to
use %, /, *.
Examples:
Input: 2
Output: 7
Input: 5
Output: 17 (Ignore the digits after decimal point)
Solution:
1. We can get x*3.5 by adding 2*x, x and x/2. To calculate 2*x, left shift x by 1 and to calculate x/2, right shift x
by 2.
#include <stdio.h>
int multiplyWith3Point5(int x)
{
return (x<<1) + x + (x>>1);
}
/* Driver program to test above functions*/
int main()
{
int x = 4;
printf("%d", multiplyWith3Point5(x));
getchar();
return 0;
}
2. Another way of doing this could be (8*x x)/2 (See below code). Thanks to ajaym for suggesting this.
#include <stdio.h>
int multiplyWith3Point5(int x)
{
return ((x<<3) - x)>>1;
}
Input:
12 (00...01100)
Output: 8 (00...01000)
Input:
7 (00...00111)
Output: 6 (00...00110)
Let the input number be n. n-1 would have all the bits flipped after the rightmost set bit (including the set bit).
So, doing n&(n-1) would give us the required result.
#include<stdio.h>
/* unsets the rightmost set bit of n and returns the result */
int fun(unsigned int n)
{
return n&(n-1);
}
/* Driver program to test above function */
int main()
{
int n = 7;
printf("The number after unsetting the rightmost set bit %d", fun(n));
getchar();
return 0;
}
Asked by Ajay
1. A simple method is to take log of the given number on base 4, and if we get an integer then number is power
of 4.
2. Another solution is to keep dividing the number by 4, i.e, do n = n/4 iteratively. In any iteration, if n%4
becomes non-zero and n is not 1 then n is not a power of 4, otherwise n is a power of 4.
#include<stdio.h>
#define bool int
/* Function to check if x is power of 4*/
bool isPowerOfFour(int n)
{
if(n == 0)
return 0;
while(n != 1)
{
if(n%4 != 0)
return 0;
n = n/4;
}
return 1;
}
/*Driver program to test above function*/
int main()
{
int test_no = 64;
if(isPowerOfFour(test_no))
printf("%d is a power of 4", test_no);
else
printf("%d is not a power of 4", test_no);
getchar();
}
3. A number n is a power of 4 if following conditions are met.
a) There is only one bit set in the binary representation of n (or n is a power of 2)
b) The count of zero bits before the (only) set bit is even.
For example: 16 (10000) is power of 4 because there is only one bit set and count of 0s before the set bit is 4
which is even.
Thanks to Geek4u for suggesting the approach and providing the code.
#include<stdio.h>
#define bool int
bool isPowerOfFour(unsigned int n)
{
int count = 0;
/*Check if there is only one bit set in n*/
if ( n && !(n&(n-1)) )
{
/* count 0 bits before set bit */
while(n > 1)
{
n
>>= 1;
count += 1;
}
/*If count is even then return true else false*/
return (count%2 == 0)? 1 :0;
}
/* If there are more than 1 bit set
then n is not a power of 4*/
return 0;
}
We need not to do anything if a number is positive. We want to change only negative numbers. Since negative
numbers are stored in 2s complement form, to get the absolute value of a negative number we have to toggle
bits of the number and add 1 to the result.
For example -2 in a 8 bit system is stored as follows 1 1 1 1 1 1 1 0 where leftmost bit is the sign bit. To get the
absolute value of a negative number, we have to toggle all bits and add 1 to the toggled number i.e, 0 0 0 0 0 0
0 1 + 1 will give the absolute value of 1 1 1 1 1 1 1 0. Also remember, we need to do these operations only if
the number is negative (sign bit is set).
Method 1
1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
mask = n>>31
2) For negative numbers, above step sets mask as 1 1 1 1 1 1 1 1 and 0 0 0 0 0 0 0 0 for positive numbers. Add
the mask to the given number.
mask + n
3) XOR of mask +n and mask gives the absolute value.
(mask + n)^mask
Implementation:
#include <stdio.h>
#define CHAR_BIT 8
/* This function will return absoulte value of n*/
unsigned int getAbs(int n)
{
int const mask = n >> (sizeof(int) * CHAR_BIT - 1);
return ((n + mask) ^ mask);
}
/* Driver program to test above function */
int main()
{
int n = -6;
printf("Absoute value of %d is %u", n, getAbs(n));
getchar();
return 0;
}
Method 2:
1) Set the mask as right shift of integer by 31 (assuming integers are stored using 32 bits).
mask = n>>31
2) XOR the mask with number
mask ^ n
3) Subtract mask from result of step 2 and return the result.
(mask^n) - mask
Implementation:
Compute n modulo d without division(/) and modulo(%) operators, where d is a power of 2 number.
Let ith bit from right is set in d. For getting n modulus d, we just need to return 0 to i-1 (from right) bits of n as
they are and other bits as 0.
For example if n = 6 (00..110) and d = 4(00..100). Last set bit in d is at position 3 (from right side). So we need
to return last two bits of n as they are and other bits as 0, i.e., 00..010.
Now doing it is so easy, guess it.
Yes, you have guessing it right. See the below program.
#include<stdio.h>
On some rare machines where branching is expensive, the below obvious approach to fnd minimum can be
slow as it uses branching.
/* The obvious approach to find minimum (involves branching) */
int min(int x, int y)
{
return (x < y) ? x : y
}
Below are the methods to get minimum(or maximum) without using branching. Typically, the obvious approach
is best, though.
Method 1(Use XOR and comparison operator)
Minimum of x and y will be
It works because if x < y, then -(x < y) will be all ones, so r = y ^ (x ^ y) & ~0 = y ^ x ^ y = x. Otherwise, if x >= y,
then -(x < y) will be all zeros, so r = y ^ ((x ^ y) & 0) = y. On some machines, evaluating (x < y) as 0 or 1
requires a branch instruction, so there may be no advantage.
To fnd the maximum, use
Note that the 1989 ANSI C specifcation doesn't specify the result of signed right-shift, so above method is not
portable. If exceptions are thrown on overflows, then the values of x and y should be unsigned or cast to
unsigned for the subtractions to avoid unnecessarily throwing an exception, however the right-shift needs a
signed operand to produce all one bits when negative, so cast to signed there.
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall of at one end
are put back to the other end.
In left rotation, the bits that fall of at left end are put back at right end.
In right rotation, the bits that fall of at right end are put back at left end.
Example:
Let n is stored using 8 bits. Left rotation of n = 11100101 by 3 makes n = 00101111 (Left shifted by 3 and frst 3
bits are put back in last ). If n is stored using 16 bits or 32 bits then left rotation of n (00011100101) becomes
00..0011100101000.
Right rotation of n = 11100101 by 3 makes n = 10111100 (Right shifted by 3 and last 3 bits are put back in
frst ) if n is stored using 8 bits. If n is stored using 16 bits or 32 bits then right rotation of n (00011100101) by
3 becomes 101000..0011100.
#include<stdio.h>
#define INT_BITS 32
/*Function to left rotate n by d bits*/
int leftRotate(int n, unsigned int d)
{
/* In n<<d, last d bits are 0. To put first 3 bits of n at
last, do bitwise or of n<<d with n >>(INT_BITS - d) */
return (n << d)|(n >> (INT_BITS - d));
}
/*Function to right rotate n by d bits*/
int rightRotate(int n, unsigned int d)
{
/* In n>>d, first d bits are 0. To put last 3 bits of at
first, do bitwise or of n>>d with n <<(INT_BITS - d) */
return (n >> d)|(n << (INT_BITS - d));
}
/* Driver program to test above functions */
int main()
{
int n = 16;
int d = 2;
printf("Left Rotation of %d by %d is ", n, d);
printf("%d", leftRotate(n, d));
printf("\nRight Rotation of %d by %d is ", n, d);
printf("%d", rightRotate(n, d));
getchar();
}
Suggested by Dheeraj
Question: You are given two numbers A and B. Write a program to count number of bits needed to be flipped
to convert A to B.
Solution:
= 1001001
= 0010101
a_xor_b = 1011100
No of bits need to flipped = set bit count in a_xor_b i.e. 4
Asked by SG
Given an array in which all numbers except two are repeated once. (i.e. we have 2n+2 numbers and n numbers
are occurring twice and remaining two have occurred once). Find those two numbers in the most efficient way.
xor = arr[0]^arr[1]^arr[2].....arr[n-1]
All the bits that are set in xor will be set in one non-repeating element (x or y) and not in other. So if we take any
set bit of xor and divide the elements of the array in two sets one set of elements with same bit set and other
set with same bit not set. By doing so, we will get x in one set and y in another set. Now if we do XOR of all the
elements in frst set, we will get frst non-repeating element, and by doing same in other set we will get the
second non-repeating element.
*y = 0;
/* Get the xor of all elements */
for(i = 1; i < n; i++)
xor ^= arr[i];
/* Get the rightmost set bit in set_bit_no */
set_bit_no = xor & ~(xor-1);
/* Now divide elements in two sets by comparing rightmost set
bit of xor with bit at same position in each element. */
for(i = 0; i < n; i++)
{
if(arr[i] & set_bit_no)
*x = *x ^ arr[i]; /*XOR of first set */
else
*y = *y ^ arr[i]; /*XOR of second set*/
}
}
/* Driver program to test above function */
int main()
{
int arr[] = {2, 3, 7, 9, 11, 2, 3, 11};
int *x = (int *)malloc(sizeof(int));
int *y = (int *)malloc(sizeof(int));
get2NonRepeatingNos(arr, 8, x, y);
printf("The non-repeating elements are %d and %d", *x, *y);
getchar();
}