
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Program to 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
- Related Articles
- C++ program to find the Parity of a number efficiently
- Java program to count total bits in a number
- C# program to count total bits in a number
- Java program to reverse bits of a positive integer number
- Python program to reverse bits of a positive integer number?
- C Program for efficiently print all prime factors of a given number?
- C# program to count total set bits in a number
- Write a python program to count total bits in a number?
- Finding the Parity of a number Efficiently in C++
- Program to invert a binary tree in Python
- Write an Efficient C Program to Reverse Bits of a Number in C++
- C# Program to invert the order of elements in a sequence
- C program to rotate the bits for a given number
- JavaScript Program to Efficiently compute sums of diagonals of a matrix
- Program to find higher number with same number of set bits as n in Python?\n

Advertisements