Unit Ii
Unit Ii
SYLLABUS
Bit Manipulation: Introduction, Applications: Counting Bits,
Palindrome Permutation, Remove All Ones with Row and Column
Flips, Encode Number.
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
Introduction
In programming, an n-bit integer is internally stored as a binary number that consists of n bits.
For example, the Java type int is a 32-bit type, which means that every int number consists of 32
bits. For example, the bit representation of the int number 43 is
00000000000000000000000000101011.
Or Operation The or operation x | y produces a number that has ‘1’ bit in positions where at least one
of x and y have ‘1’ bits. For example, 22 | 26 = 30, because
10110 (22)
11010 (26) |
11110 (30)
Xor Operation The xor operation x ˆ y produces a number that has ‘1’ bit in positions where
exactly one of x and y have ‘1’ bits. For example, 22 ˆ 26=12, because
10110 (22)
11010 (26)
01100 (12)
Not Operation: The not operation ~x produces a number where all the bits of x have been
inverted. For example, ~29 is 30. The result of the not operation at the bit level depends on the
length of the bit representation, because the operation inverts all bits. For example, if the
numbers are 32-bit integers, the result is as follows:
x= 29 -> 00000000000000000000000000011101
x = −30 -> 11111111111111111111111111100010
~
Bit Shifts: The left shift x << k appends k zero bits to the number, and the right shift x >> k removes
the k last bits from the number.
For example, 14<<2=56 , because 14 and 56 correspond to 1110 and 111000.
Similarly, 49 >> 3 is 6, because 49 and 6 correspond to 110001 and 110.
x << k corresponds to multiplying x by 2k, and
x >> k corresponds to dividing x by 2k rounded down to an integer.
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
Bit manipulation is the process of applying logical operations on a sequence of bits, the smallest form
of data in a computer, to achieve a required result. Bit manipulation has constant time complexity and
process in parallel, meaning it is very efficient on all systems.
Most programming languages will have you work with abstractions, like objects or variables, rather
than the bits they represent. However, direct bit manipulation is needed to improve performance and
reduce error in certain situations.
Bit manipulation requires a strong knowledge of binary and binary conversion.
Here’s a few examples of tasks that require bit manipulation:
➢ Low-level device control
➢ Error detection and correction algorithms
➢ Data compression
➢ Encryption algorithms
➢ Optimization
For example, take a look at the difference between an arithmetic and bit manipulation approach for
finding the green portion of an RGB value:
//arithmetic
(rgb / 256) % 256
// bit
(rgb >> 8) & 0xFF
While both do the same thing, the second option is considerably faster, as it works directly within
memory rather than through a level of abstraction.
We’ll explore what each of these operators do later in this article (>> and &).
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
Bitwise Operators
Bitwise operations take one or more bit-patterns or binary numerals and manipulate them at the bit
level. They’re essentially our tool to manipulate bits to achieve our operations.
While arithmetic operations perform operations on human-readable values (1+2), bitwise operators
manipulate the low-level data directly.
Formula: x=232–x
Example:
class NOTOperation
{
public static void main( String args[] )
{
int a = 1;
System.out.println("Bitwise NOT of a is : " + ~a);
}
}
Output:
Bitwise NOT of a is : -2
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
Bitwise Exclusive OR (XOR) (^) Operator
The bitwise XOR operation (^), short for “Exclusive-Or”, is a binary operator that takes two input
arguments and compares each corresponding bit. If the bits are opposite, the result has a 1 in that bit
position. If they match, a 0 is returned.
1 ^ 1 => yields to 0.
0 ^ 0 => yields to 0.
1 ^ 0 => yields to 1.
0 ^ 1 => yields to 1.
For example:
a = 12
b = 10
------------------------------------------
a in binary : 0000 0000 0000 1100
b in binary : 0000 0000 0000 1010
------------------------------------------
a^b : 0000 0000 0000 0110
------------------------------------------
XOR is used to invert selected individual bits in a register or manipulate bit patterns that represent
Boolean states.
XOR is also sometimes used to set the value of a registry to zero as XOR with two of the same input
will always result in 0.
Example:
class XOROperation
{
public static void main( String args[] )
{
int x = 12;
int y = 10;
System.out.println("Bitwise XOR of (x , y) is : " + (x ^ y)); // yields to 6
}
}
Output:
Bitwise XOR of (x , y) is : 6
As you can see, the digits have shifted to the left by one position, and the last digit on the right is filled
with a zero. Note that shifting left is equivalent to multiplication by powers of 2.
6 << 1→ 6∗21 → 6∗2
6 << 3 → 6∗23 → 6∗8
Well-optimized compilers will use this rule to replace multiplication with shifts whenever possible, as
shifts are faster.
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
Example:
class LeftShift
{
private static int helper(int number, int i)
{
return number << i;// multiplies `number` with 2^i times.
}
public static void main(String[] args)
{
int number = 100;
System.out.println(number + " shifted 1 position left, yields to " + helper(number, 1));
System.out.println(number + " shifted 2 positions left, yields to " + helper(number, 2));
System.out.println(number + " shifted 3 positions left, yields to " + helper(number, 3));
System.out.println(number + " shifted 4 positions left, yields to " + helper(number, 4));
}
}
Output:
100 shifted 1 position left, yields to 200
100 shifted 2 positions left, yields to 400
100 shifted 3 positions left, yields to 800
100 shifted 4 positions left, yields to 1600
With right shift, you can either do arithmetic (>>) or logical (>>) shift.
The difference is that arithmetic shifts maintain the same most significant bit (MSB) or sign bit, the
leftmost bit which determines if a number is positive or negative.
10110101 >>1 = 1101 1010.
Formula: x >>y = x/2y
On the other hand, a logical shift simply moves everything to the right and replaces the MSB with a 0.
10110101>>>1= 01011010
Formula: a >>b = a/2b
Example:
class RightShift
{
public static void main(String[] args)
{
int number1 = 8;
int number2 = -8;
// 2-bit signed right shift
System.out.println(number1 >> 2); // prints 2
System.out.println(number2 >> 2); // prints -2
}
}
Output:
2
-2
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
Output:
Toggle case: cHErRy
Original string: CheRrY
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
Using Bitwise AND: Java program to count the number of bits set to 1 (set bits) of a
given integer
In this approach, we count only the set bits. So,
If a number has 2 set bits, then the while loop runs two times.
If a number has 4 set bits, then the while loop runs four times.
✓ Our while loop iterates until n = 0, dividing by 2 each time via the AND operator.
✓ On pass 1, 125 becomes 62, and count increases by 1.
✓ On the second pass, 62 becomes 31, and the count increases to 2.
✓ This continues until n becomes 0 and the count is then returned.
Program:
class CountSetBit
{
private static int helper(int n)
{
int count = 0;
while (n > 0)
{
n &= (n - 1);
count++;
}
return count;
}
Output:
Element appearing one time is 9
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
Using Bitwise Left Shift: Get First Set BitGiven an integer, find the position of the
first set-bit (1) from the right.
Input: n = 18
18 in binary = 0b10010
Output: 2
Procedure:
The logic of this solution relies on a combination of left shifting and the AND operation.
Essentially, we first check if the rightmost significant bit is the set bet using bit & 1. If not, we keep
shifting left and checking until we find the bit that makes our AND operation yield 1.
The number of shifts is tracked by our pointer, k. Once we do find the set bit, we return k as our
answer.
Program
class FirstSetBitPosition
{
private static int helper(int n)
{
if (n == 0)
{
return 0;
}
int k = 1;
while (true)
{
if ((n & (1 << (k - 1))) == 0)
{
k++;
}
else
{
return k;
}
}
}
public static void main(String[] args)
{
System.out.println("First setbit position for number: 18 is -> " + helper(18));
System.out.println("First setbit position for number: 5 is -> " + helper(5));
System.out.println("First setbit position for number: 32 is -> " + helper(32));
}
}
Output:
First setbit position for number: 18 is -> 2
First setbit position for number: 5 is -> 1
First setbit position for number: 32 is -> 6
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
input=
Enter the first number: 7
Enter the second number: 9
output=
Before swapping:
79
After swapping:
97
Complexity Analysis
Applications
✓ Counting Bits
✓ Palindrome Permutation
✓ Remove All Ones with Row and Column Flips
✓ Encode Number.
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
1. Counting Bits
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is
the number of 1's in the binary representation of i.
Input: n = 2
Output: [0,1,1] Explanation:
0 --> 0
1 --> 1
2 --> 10
Input: n = 5
Output: [0,1,1,2,1,2]
Explanation:
0 --> 0
1 --> 1
2 --> 10
3 --> 11
4 --> 100
5 --> 101
Procedure:
1. Since for decimal number 0 , no. of '1' bits in its binary representation = 0
2. For each value from 1 loop to iterate each bit of the number and count no. of '1' bits till the
number becomes 0 i.e.it has no '1' bits remaining in its binary representation.
3. 0 will be added to count if last bit is 0 , and 1 will be added to count variable if last bit is 1,
thereby increasing count to 1.
4. Drop the last bit and repeat the process of counting the 1 bit.
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
Write a Java Program to count the number of 1 in bit representation from 0 to a given value
CountingBits.java
import java.util.*;
class CountingBits
{
public static int[] countBits(int n)
{
int r[]= new int[n+1];
r[0]=0;
for(int i=1; i<=n; i++)
{
int ct=0; int x=i;
while(x>0)
{
ct+= (x & 1);
x= x >> 1;
}
r[i]= ct;
}
return r;
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
int n=s.nextInt();
int r[]=new int[n+1];
r=countBits(n);
for(int i=0;i<=n;i++)
System.out.println(" "+r[i]);
}
}
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
2. Palindrome Permutation
Given a string, determine if a permutation of the string could form a palindrome.
Example 1:
Input: "code"
Output: false
Example 2:
Input: "aab"
Output: true
Example 3:
Input: "carerac"
Output: true
If a string with an even length is a palindrome, every character in the string must always occur
even number of times. If the string with an odd length is a palindrome, every character except one
of the characters must occur even number of times. Thus, in case of a palindrome, the number of
characters with odd number of occurrences can't exceed 1 (1 in case of odd length and 0 in case of
even length).
Procedure:
PermutePalindrome.java
import java.util.*;
class PermutePalindrome
{
static boolean canPermutePalindrome(String s)
{
int bitmask = 0;
for(int i=0;i<s.length();i++)
{
char ch=s.charAt(i);
bitmask = bitmask ^ (1 << (ch - 'a'));
}
return (bitmask == 0 || (bitmask & (bitmask-1)) == 0 );
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println(“Enter the string”);
String ps=s.next();
System.out.println(canPermutePalindrome(ps));
}
}
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
3. Remove All Ones with Row and Column Flips
We are given an m x n binary matrix grid.
In one operation, you can choose any row or column and flip each value in that row or column (i.e.,
changing all 0's to 1's, and all 1's to 0's).
Return true if it is possible to remove all 1’s from the grid using any number of operations or false
otherwise.
Java Program to determine whether it is possible to remove all 1’s from a binary matrix with
row and column flips.
import java.util.*;
class RowColFlips
{
public boolean removeOnes(int[][] grid)
{
// if the matrix only has one row then it is always true
if (grid.length <= 1) return true;
// start with the second row compare all values to the first row
for (int i=1; i<grid.length; i++)
{
if (!equalsOrComplement(grid[0], grid[i]))
return false;
}
return true;
}
System.out.println(new RowColFlips().removeOnes(grid));
}
}
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
4. Encode Number
Given a non-negative integer num, Return its encoding string.
The encoding is done by converting the integer to a string using a secret function that you should
deduce from the following table:
N f(n)
0 “”
1 “0”
2 “1”
3 “00”
4 “01”
5 “10”
6 “11”
7 “000”
Example 1:
Input: num = 23
Output: “1000”
Example 2:
Input: num = 107
Output: “101100”
If n is 0, then f(n) is "". If 1 <= n < 3, then f(n) is a binary string with length 1. If 3
<= n < 7, then f(n) is a binary string with length 2. If 7 <= n < 15, then `f(n) is a binary string
with length 3.
Procedure
1. For the given number num, obtain the number of bits bits for number num + 1, where the
number of bits means the number of bits remaining after removing leading zeros.
2. Calculate difference as the difference between num + 1 and 2 ^ bits, and return the binary
representation of difference.
COMPETITIVE PROGRAMMING UNIT-II III-II SEM
EncodeNumber.java
import java.util.*;
class EncodeNumber
{
public String encode(int num)
{
StringBuilder sb = new StringBuilder();
double cur = Math.log(num + 1) / Math.log(2);
int bits = (int)(Math.floor(cur));
int offset = num - (int)(Math.pow(2, bits)) +1;
while (offset > 0)
{
sb.append(offset % 2);
offset /= 2;
}
int l = sb.length();
for (int i = l; i < bits; i++)
{
ssb.append("0");
}
return sb.reverse().toString();
}