Bit Manipulation and Time Complexity

Bitwise operators, bit manipulation tricks, and Big-O complexity analysis.


Java bitwise operators: & (AND), | (OR), ^ (XOR), ~ (NOT); << and >> shift bits left and right. Common tricks: (n & 1) tests parity, x ^ 1 toggles the lowest bit, a mask like 0xFF extracts a byte, and (n & (n-1)) == 0 detects a power of two. Big-O measures runtime growth with input size: O(1) constant, O(log n) for binary search, O(n) for a linear scan, O(n log n) for efficient sorts and O(n^2) for nested loops.

Example
if((n & 1) == 0) System.out.println("even");
Video Lesson Open in new tab
Quiz
1. What is the value of the expression 5 & 3 in Java?
2. What is the result of applying the XOR operator to 5 and 3 (5 ^ 3)?
3. Which expression is true if and only if the integer n is even?
4. What exact effect does evaluating x << 2 have on the integer value x?
5. What is the worst-case time complexity of binary search over a sorted array of n elements?
6. Which bit trick does the standard way to check whether a positive integer n is a power of two rely on?
Coding Problems
1. Write a Java method that returns true when the integer n is a power of two using the bit trick ((n & (n-1)) == 0), returns false when n is not positive, and print the result for n=16.
Discussion

Login to join the discussion.


No comments yet.