Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Bitwise Algorithms
  • MCQs on Bitwise Algorithms
  • Tutorial on Biwise Algorithms
  • Binary Representation
  • Bitwise Operators
  • Bit Swapping
  • Bit Manipulation
  • Count Set bits
  • Setting a Bit
  • Clear a Bit
  • Toggling a Bit
  • Left & Right Shift
  • Gray Code
  • Checking Power of 2
  • Important Tactics
  • Bit Manipulation for CP
  • Fast Exponentiation
Open In App
Next Article:
Bitwise Hacks for Competitive Programming
Next article icon

Bit Tricks for Competitive Programming

Last Updated : 24 Nov, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

In competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.
Bitwise Hacks for Competitive Programming

One-Liner Hacks of Bit Manipulation:

One-Liner Code

Function

x&1

Evaluates to 1 if the number is odd else evaluates to 0

x & (x-1)

Clears the lowest set bit of x

x & ~(x-1)

Extracts the lowest set bit of x (all others are cleared)

x & ~((1 << i+1 ) – 1)

Clears all bits of x from LSB to ith bit

x & ((1 << i) – 1)

Clears all bits of x from MSB to ith bit

x >>1

Divides x by 2

x << 1

Multiplies x by 2 

ch | ‘ ‘

Upper case English alphabet ch to lower case

ch & ‘_’

Lower case English alphabet ch to upper case

x && !(x & x-1)

Checking if given 32-bit integer is power of 2

log2(n & -n)+1

Find the last set bit

1) Check Whether Number is Even or Odd 

x & 1 

Logic:
Even numbers have 0 as their LSB and Odd numbers have 1 as their LSB, so Bitwise AND with even numbers results in 0 and with odd numbers results in 1. 
Example:
x = 29 (00011101), (x & 1) = 1, therefore x is an odd number
x= 16(10000), (x & 1) = 0, therefore x is an even number

2) Clear the Lowest Set bit of x

 x & (x-1) 

Logic:
When you subtract 1 from x, all the bits to the right of the lowest set bit become 1, and the lowest set bit becomes 0 and performing a bitwise AND operation between x and (x-1) sets each bit to 0 except for the bits that are common in both x and (x-1). 
Example:
x = 10101010
x-1 = 10101001
x & (x-1) = 10101000

3) Extract the Lowest Set bit of x

x & ~(x-1); 

Logic:
When you subtract 1 from x, all the bits to the right of the lowest set bit become 1, and the lowest set bit becomes 0 and performing a bitwise AND operation between x and ~(x-1) sets each bit to 0 except for the lowest set bit of x.
Example:
x = 10101010
~(x-1) = 01010110
x & ~(x-1) = 00000010

4) Clear all bits from LSB to ith bit 

mask = ~((1 << i+1 ) - 1); x &= mask; 

Logic:
To clear all bits from LSB to i-th bit, we have to AND x with mask having LSB to i-th bit 0. To obtain such mask, first left shift 1 i times. Now if we minus 1 from that, all the bits from 0 to i-1 become 1 and remaining bits become 0. Now we can simply take the complement of mask to get all first i bits to 0 and remaining to 1. 
Example:– 
x = 29 (00011101) and we want to clear LSB to 3rd bit, total 4 bits 
mask -> 1 << 4 -> 16(00010000) 
mask -> 16 – 1 -> 15(00001111) 
mask -> ~mask -> 11110000 
x & mask -> 16 (00010000)

5) Clearing all bits from MSB to i-th bit 

mask = (1 << i) - 1; x &= mask; 

Logic:
To clear all bits from MSB to i-th bit, we have to AND x with mask having MSB to i-th bit 0. To obtain such mask, first left shift 1 i times. Now if we minus 1 from that, all the bits from 0 to i-1 become 1 and the remaining bits become 0. 
Example: 
x = 215 (11010111) and we want to clear MSB to 4th bit, total 4 bits 
mask -> 1 << 4 -> 16(00010000) 
mask -> 16 – 1 -> 15(00001111) 
x & mask -> 7(00000111)

6) Divide by 2 

x >>= 1; 

Logic:
When we do arithmetic right shift, every bit is shifted to right and blank position is substituted with sign bit of number, 0 in case of positive and 1 in case of negative number. Since every bit is a power of 2, with each shift we are reducing the value of each bit by factor of 2 which is equivalent to division of x by 2. 
Example: 
x = 18(00010010) 
x >> 1 = 9 (00001001)

7) Multiplying by 2 

x <<= 1; 

Logic:
When we do arithmetic left shift, every bit is shifted to left and blank position is substituted with 0 . Since every bit is a power of 2, with each shift we are increasing the value of each bit by a factor of 2 which is equivalent to multiplication of x by 2. 
Example: 
x = 18(00010010) 
x << 1 = 36 (00100100)

8) Upper case English alphabet to lower case 

ch |= ' '; 

Logic: The bit representation of upper case and lower case English alphabets are – 

A -> 01000001          a -> 01100001 B -> 01000010          b -> 01100010 C -> 01000011          c -> 01100011   .                               .   .                               . Z -> 01011010          z -> 01111010 

As we can see if we set 5th bit of upper case characters, it will be converted into lower case character. We have to prepare a mask having 5th bit 1 and other 0 (00100000). This mask is bit representation of space character (‘ ‘). The character ‘ch’ then OR with mask.
Example: 
ch = ‘A’ (01000001) 
mask = ‘ ‘ (00100000) 
ch | mask = ‘a’ (01100001) 
Please refer Case conversion (Lower to Upper and Vice Versa) for details.

9) Lower case English alphabet to upper case 

ch &= '_’ ; 

Logic: The bit representation of upper case and lower case English alphabets are – 

A -> 01000001                a -> 01100001 B -> 01000010                b -> 01100010 C -> 01000011                c -> 01100011 .                               . .                               . Z -> 01011010                z -> 01111010 

As we can see if we clear 5th bit of lower-case characters, it will be converted into upper case character. We have to prepare a mask having 5th bit 0 and other 1 (11011111). This mask is bit representation of underscore character (‘_‘). The character ‘ch’ then AND with mask. 
Example: 
ch = ‘a’ (01100001) 
mask = ‘_ ‘ (11011111) 
ch & mask = ‘A’ (01000001) 
Please refer Case conversion (Lower to Upper and Vice Versa) for details.

10) Count set bits in integer 

int countSetBits(int x) {     int count = 0;     while (x)     {         x &= (x-1);         count++;     }     return count; } 

Logic: This is Brian Kernighan’s algorithm.

11) Find log base 2 of 32 bit integer 

int log2(int x) {     int res = 0;     while (x >>= 1)         res++;     return res; } 

Logic: We right shift x repeatedly until it becomes 0, meanwhile we keep count on the shift operation. This count value is the log2(x).

12) Checking if given 32-bit integer is power of 2 

int isPowerof2(int x) {     return (x && !(x & x-1)); } 

Logic:
All the power of 2 have only single bit set e.g. 16 (00010000). If we minus 1 from this, all the bits from LSB to set bit get toggled, i.e., 16-1 = 15 (00001111). Now if we AND x with (x-1) and the result is 0 then we can say that x is power of 2 otherwise not. We have to take extra care when x = 0.
Example :
x = 16(00010000) 
x – 1 = 15(00001111) 
x & (x-1) = 0 
so, 16 is power of 2

13) Find the last set bit

int lastSetBit(int n){     return log2(n & -n)+1; } 

The logarithmic value of AND of x and -x to the base 2 gives the index of the last set bit(for 0-based indexing).

Playing with Kth bit:

1) Turn Off kth bit in a number

int turnOffKthBit(int n, int k) {     return n & ~(1 << (k - 1)); } 

2) Turn On kth bit in a number

int turnOnKthBit(int n, int k) {     return n | (1 << (k - 1)); } 

3) Check if kth bit is set for a number

bool isKthBitSet(int n, int k) {     return (n & (1 << (k - 1))) != 0; } 

4) Toggle the kth bit

int toggleKthBit(int n, int k) {     return n ^ (1 << (k - 1)); }

Please refer this article for more bit hacks.


 



Next Article
Bitwise Hacks for Competitive Programming

A

Atul Kumar
Improve
Article Tags :
  • Bit Magic
  • Competitive Programming
  • DSA
Practice Tags :
  • Bit Magic

Similar Reads

  • Competitive Programming - A Complete Guide
    Competitive Programming is a mental sport that enables you to code a given problem under provided constraints. The purpose of this article is to guide every individual possessing a desire to excel in this sport. This article provides a detailed syllabus for Competitive Programming designed by indust
    8 min read
  • Competitive Programming (CP) Handbook with Complete Roadmap
    Welcome to the Competitive Programming Handbook or CP Handbook by GeeksforGeeks! This Competitive Programming Handbook is a go-to resource for individuals aiming to enhance their problem-solving skills and excel in coding competitions. This CP handbook provides a comprehensive guide, covering fundam
    12 min read
  • Mathematics for Competitive Programming

    • Must do Math for Competitive Programming
      Competitive Programming (CP) doesn’t typically require one to know high-level calculus or some rocket science. But there are some concepts and tricks which are sufficient most of the time. You can definitely start competitive coding without any mathematical background, but maths becomes essential as
      15+ min read

    • Pigeonhole Principle for CP | Identification, Approach & Problems
      In competitive programming, where people solve tough problems with computer code, the Pigeonhole Principle is like a secret tool. Even though it's a simple idea, it helps programmers tackle complex challenges. This article is your guide to understanding how this principle works and why it's crucial
      8 min read

    • Euler Totient for Competitive Programming
      What is Euler Totient function(ETF)?Euler Totient Function or Phi-function for 'n', gives the count of integers in range '1' to 'n' that are co-prime to 'n'. It is denoted by [Tex]\phi(n) [/Tex].For example the below table shows the ETF value of first 15 positive integers: 3 Important Properties of
      8 min read

    • Mathematics for Competitive Programming Course By GeeksforGeeks
      Mathematics forms the foundation of problem-solving in Competitive Programming (CP). Mastering key mathematical concepts is crucial for approaching algorithmic challenges effectively. If you're an aspiring competitive programmer or someone who wishes to enhance your problem-solving skills, this Math
      3 min read

    Number Theory for CP

    • Binary Exponentiation for Competitive Programming
      In competitive programming, we often need to do a lot of big number calculations fast. Binary exponentiation is like a super shortcut for doing powers and can make programs faster. This article will show you how to use this powerful trick to enhance your coding skills. Table of ContentWhat is Binary
      15+ min read

    • GCD (Greatest Common Divisor) Practice Problems for Competitive Programming
      GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest positive integer that divides both of the numbers. Fastest Way to Compute GCDThe fastest way to find the Greatest Common Divisor (GCD) of two numbers is by using the Euclidean algorithm. The Euclidean algorith
      4 min read

    Bit Manipulation for CP

    • Bit Manipulation for Competitive Programming
      Bit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usag
      15+ min read

    • Bit Tricks for Competitive Programming
      In competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.Bitwise Hacks for Competitive Programming One-Liner Hacks of Bit Manipulation:One-Liner CodeFunctionx&1
      7 min read

    • Bitwise Hacks for Competitive Programming
      Prerequisite: It is recommended to refer Interesting facts about Bitwise Operators How to set a bit in the number 'num': If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ). First, we left shift '1' to n position via (1<<n)Then, use the 'OR'
      14 min read

    Combinatorics for CP

    • Inclusion Exclusion principle for Competitive Programming
      What is the Inclusion-Exclusion Principle?The inclusion-exclusion principle is a combinatoric way of computing the size of multiple intersecting sets or the probability of complex overlapping events. Generalised Inclusion-Exclusion over Set:For 2 Intersecting Set A and B: [Tex]A\bigcup B= A + B - A\
      5 min read

    Greedy for CP

    • Binary Search on Answer Tutorial with Problems
      Binary Search on Answer is the algorithm in which we are finding our answer with the help of some particular conditions. We have given a search space in which we take an element [mid] and check its validity as our answer, if it satisfies our given condition in the problem then we store its value and
      15+ min read

    • Ternary Search for Competitive Programming
      Ternary search is a powerful algorithmic technique that plays a crucial role in competitive programming. This article explores the fundamentals of ternary search, idea behind ternary search with its use cases that will help solving complex optimization problems efficiently. Table of Content What is
      8 min read

    Array based concepts for CP

    • What are Online and Offline query-based questions in Competitive Programming
      The query-based questions of competitive programming are mainly of two types: Offline Query.Online Query. Offline Query An offline algorithm allows us to manipulate the data to be queried before any answer is printed. This is usually only possible when the queries do not update the original element
      4 min read

    • Precomputation Techniques for Competitive Programming
      What is the Pre-Computation Technique?Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations or data stru
      15+ min read

    • PreComputation Technique on Arrays
      Precomputation refers to the process of pre-calculating and storing the results of certain computations or data structures(array in this case) in advance, in order to speed up the execution time of a program. This can be useful in situations where the same calculations are needed multiple times, as
      15 min read

    • Frequency Measuring Techniques for Competitive Programming
      Measuring the frequency of elements in an array is a really handy skill and is required a lot of competitive coding problems. We, in a lot of problems, are required to measure the frequency of various elements like numbers, alphabets, symbols, etc. as a part of our problem. Examples: Input: arr[] =
      15+ min read

    Dynamic Programming (DP) for CP

    • DP on Trees for Competitive Programming
      Dynamic Programming (DP) on trees is a powerful algorithmic technique commonly used in competitive programming. It involves solving various tree-related problems by efficiently calculating and storing intermediate results to optimize time complexity. By using the tree structure, DP on trees allows p
      15+ min read

    • Dynamic Programming in Game Theory for Competitive Programming
      In the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive e
      15+ min read

    Game Theory for CP

    • Interactive Problems in Competitive Programming
      Interactive Problems are those problems in which our solution or code interacts with the judge in real time. When we develop a solution for an Interactive Problem then the input data given to our solution may not be predetermined but is built for that problem specifically. The solution performs a se
      6 min read

    • Mastering Bracket Problems for Competitive Programming
      Bracket problems in programming typically refer to problems that involve working with parentheses, and/or braces in expressions or sequences. It typically refers to problems related to the correct and balanced usage of parentheses, and braces in expressions or code. These problems often involve chec
      4 min read

    • MEX (Minimum Excluded) in Competitive Programming
      MEX of a sequence or an array is the smallest non-negative integer that is not present in the sequence. Note: The MEX of an array of size N cannot be greater than N since the MEX of an array is the smallest non-negative integer not present in the array and array having size N can only cover integers
      15+ min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences