
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Invert Bits of a Number Efficiently in C++
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.
Example
#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; }
Output
14
Advertisements