# Category Archives: Bit Magic

Write a program to find the smallest of three integers, without using any of the comparison operators. Let 3 input numbers be x, y and z.Method… Read More
Input: A array arr[] of two elements having value 0 and 1Output: Make both elements 0.  Specifications: Following are the specifications to follow. 1) It… Read More
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… Read More
Given a number x, find next number with same number of 1 bits in it’s binary representation.For example, consider x = 12, whose binary representation… Read More
Modulus operator is costly. The modulus operator (%) in various languages is costly operation. Ultimately every operator/operation must result in processor instructions. Some processors won’t… Read More
Write a program to add one to a given number. The use of operators like ‘+’, ‘-‘, ‘*’, ‘/’, ‘++’, ‘–‘ …etc are not allowed. Examples: … Read More
Given an integer x, write a function that multiplies x with 3.5 and returns the integer result. You are not allowed to use %, /,… Read More
Write a program that unsets the rightmost set bit of an integer. Examples :   Input: 12 (00...01100) Output: 8 (00...01000) Input: 7 (00...00111) Output: 6 (00...00110)… Read More
Given an integer n, find whether it is a power of 4 or not. Example :  Input : 16 Output : 16 is a power… Read More
We need not to do anything if a number is positive. We want to change only negative numbers. Since negative numbers are stored in 2’s… Read More
Compute n modulo d without division(/) and modulo(%) operators, where d is a power of 2 number.  Input: 6 4 Output: 2 Explanation: As 6%4… Read More
On some rare machines where branching is expensive, the below obvious approach to find minimum can be slow as it uses branching. C++ /* The… Read More
Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put… Read More
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 the… Read More
Given two numbers A and B. Write a program to count the number of bits needed to be flipped to convert A to B.  Examples: … Read More