SET - 13 (Based On Bit Manipulation) PDF
SET - 13 (Based On Bit Manipulation) PDF
Next Power of 2
Write a function that, for a given no n, finds a number p which is greater than or equal to n and is a power
of 2.
IP 5
OP 8
IP 17
OP 32
IP 32
OP 32
O/P 2
O/P 1
A = 1001001
B = 0010101
Input: 12 (00...01100)
Output: 8 (00...01000)
Input: 7 (00...00111)
Output: 6 (00...00110)
Input: n = 3
Output: 4
Input: n = 6
Output: 9
Input: n = 7
Output: 12
Input: n = 8
Output: 13
Output: 2
Input: n = 15, k = 1
Output: 14
Input: n = 15, k = 2
Output: 13
Input: n = 15, k = 3
Output: 11
Input: n = 15, k = 4
Output: 7
Input: n = 15, k >= 5
Output: 15
Input: n = 5
Output: 25
Input: 7
Output: 49
Input: n = 12
Output: 144
Input: n = 2 Output: 25
Input: x = 12
Output: false
Explanation: Binary representation of 12 is 1100.
Sum of bit differences among all pairs
Given an integer array of n integers, find sum of bit differences in all pairs that can be formed from array
elements. Bit difference of a pair (x, y) is count of different bits at same positions in binary representations
of x and y.
For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 ( first and last
bits differ in two numbers).
Examples:
Output: 4
2 + 0
= 4
Output: 8
1 + 0 + 2 +
1 + 2 + 0
= 8
Input: x = 6
Output: 7
Output: 15
Examples:
Output: 15
= 0 + 5 + 10
= 15
Output: 3
= 0 + 1 + 0 + 2 + 0 + 0
= 3
Output: 7
Output: 13
Output: 15
Output: 6
Input : n = 2
Output : 1
Input : n = 3
Output : 3
Input : n = 5
Output : 19
Check if a number is Bleak
A number ‘n’ is called Bleak if it cannot be represented as sum of a positive number x and set bit count in
x, i.e., x + countSetBits(x) is not equal to n for any non-negative number x.
Examples :
Input : n = 3
Output : false
as 2 + countSetBits(2).
Input : n = 4
Output : true
Output : x = 14
Input : x = 8, y = 7, l = 1, r = 2
Output : x = 11
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)
00 01 11 10
0000 0001 0011 0010 0110 0111 0101 0100 1100 1101 1111