# Category Archives: Bit Magic

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 : Attention reader! Don’t stop learning now. Get hold of all… 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. Let ith bit from right is set in d.… Read More
On some rare machines where branching is expensive, the below obvious approach to find minimum can be slow as it uses branching.Attention reader! Don’t stop… 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
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… Read More
Given two numbers ‘a’ and b’. Write a program to count number of bits needed to be flipped to convert ‘a’ to ‘b’. Example :   Input… Read More
Write an efficient program to count the number of 1s in the binary representation of an integer. Examples : Attention reader! Don’t stop learning now.… Read More
Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Input : n = 1 Output : 2147483648 On… Read More
What are these? Little and big endian are two ways of storing multibyte data-types ( int, float, etc). In little endian machines, last byte of… Read More