Program to invert bits of a number Efficiently in C++

C++Server Side ProgrammingProgramming

In this tutorial, we will be discussing a program to invert bits of a number efficiently.

For this we will be given with a non-negative number. Our task is to convert the number in the binary format, invert the binary bits of the number. And then finally print the decimal equivalent of the number.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
//inverting bits of number
int invert_bit(int n){
   int x = log2(n) ;
   int m = 1 << x;
   m = m | m - 1;
   n = n ^ m;
   return n;
int main(){
   int n = 17;
   cout << invert_bit(n) << endl;
   return 0;


Updated on 19-Dec-2019 10:02:48