Invert actual bits of a number - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Invert actual bits of a number
Program to invert bits of a number Efficiently
Reverse actual bits of the given number
Write an Efficient C Program to Reverse Bits of a Number
Reverse bits using lookup table in O(1) time
A Program to check if strings are rotations of each other or not
Check if strings are rotations of each other or not | Set 2
Check if a string can be obtained by rotating another string 2 places
Converting Roman Numerals to Decimal lying between 1 to 3999
Converting Decimal Number lying between 1 to 3999 to Roman Numerals
Count ‘d’ digit positive integers with 0 as a digit
Count number of bits to be flipped to convert A to B
Count set bits in an integer
Count total set bits in all numbers from 1 to n
Count total set bits in all numbers from 1 to n | Set 2
Count total set bits in all numbers from 1 to N | Set 3
Count total unset bits in all the numbers from 1 to N
Count unset bits of a number
Count unset bits in a range
Unset bits in the given range
Find the largest number with n set and m unset bits
Find the smallest number with n set and m unset bits
Sum of numbers with exactly 2 bits set
Check if binary representation of a given number and its complement are anagram
Check a number is odd or even without modulus operator
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
How to swap two numbers without using a temporary variable?
Invert actual bits of a number
Program to invert bits of a number Efficiently
Reverse actual bits of the given number
Write an Efficient C Program to Reverse Bits of a Number
Reverse bits using lookup table in O(1) time
A Program to check if strings are rotations of each other or not
Check if strings are rotations of each other or not | Set 2
Check if a string can be obtained by rotating another string 2 places
Converting Roman Numerals to Decimal lying between 1 to 3999
Converting Decimal Number lying between 1 to 3999 to Roman Numerals
Count ‘d’ digit positive integers with 0 as a digit
Count number of bits to be flipped to convert A to B
Count set bits in an integer
Count total set bits in all numbers from 1 to n
Count total set bits in all numbers from 1 to n | Set 2
Count total set bits in all numbers from 1 to N | Set 3
Count total unset bits in all the numbers from 1 to N
Count unset bits of a number
Count unset bits in a range
Unset bits in the given range
Find the largest number with n set and m unset bits
Find the smallest number with n set and m unset bits
Sum of numbers with exactly 2 bits set
Check if binary representation of a given number and its complement are anagram
Check a number is odd or even without modulus operator
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
How to swap two numbers without using a temporary variable?
Difficulty Level :
Easy
Given a non-negative integer n. The problem is to invert the bits of n and print the number obtained after inverting the bits. Note that the actual binary representation of the number is being considered for inverting the bits, no leading 0’s are being considered.  
Examples: 
Input : 11
Output : 4
(11)10 = (1011)[2]
After inverting the bits, we get:
(0100)2 = (4)10.

Input : 10
Output : 5
(10)10 = (1010)2.
After reversing the bits we get:
(0101)2 = (101)2
        = (5)10.
Method 1 (Using bitwise operators)Prerequisite: Toggling k-th bit of a number  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to invert actual bits// of a number.#include <bits/stdc++.h>using namespace std; void invertBits(int num){    // calculating number of bits    // in the number    int x = log2(num) + 1;     // Inverting the bits one by one    for (int i = 0; i < x; i++)       num = (num ^ (1 << i));      cout << num;} // Driver codeint main(){    int num = 11;    invertBits(num);    return 0;}
// Java program to invert// actual bits of a number.import java.io.*; class GFG{    static void invertBits(int num)    {        // calculating number of        // bits in the number        int x = (int)(Math.log(num) /                      Math.log(2)) + 1;             // Inverting the        // bits one by one        for (int i = 0; i < x; i++)        num = (num ^ (1 << i));             System.out.println(num);    }         // Driver code    public static void main (String[] args)    {        int num = 11;        invertBits(num);    } } // This code is contributed// by Anuj_67
# Python3 program to invert actual# bits of a number.import math def invertBits(num):     # calculating number of bits    # in the number    x = int(math.log2(num)) + 1     # Inverting the bits one by one    for i in range(x):        num = (num ^ (1 << i))         print(num) # Driver Codenum = 11invertBits(num) # This code is contributed# by Rituraj Jain
// C# program to invert// actual bits of a number.using System; class GFG{    static void invertBits(int num)    {        // calculating number of        // bits in the number        int x = (int)(Math.Log(num) /                       Math.Log(2)) + 1;             // Inverting the        // bits one by one        for (int i = 0; i < x; i++)        num = (num ^ (1 << i));             Console.WriteLine(num);    }         // Driver code    public static void Main ()    {        int num = 11;        invertBits(num);    } } // This code is contributed// by Anuj_67
<?php// PHP program to invert actual bits// of a number. function invertBits( $num){         // calculating number of bits    // in the number    $x = log($num) + 1;     // Inverting the bits one by one    for($i = 0; $i < $x; $i++)    $num = ($num ^ (1 << $i));     echo $num;}     // Driver code    $num = 11;    invertBits($num);     // This code is contributed by anuj_67.?>
<script>     // Javascript program to invert    // actual bits of a number.         function invertBits(num)    {        // calculating number of        // bits in the number        let x =        parseInt(Math.log(num) / Math.log(2), 10) + 1;               // Inverting the        // bits one by one        for (let i = 0; i < x; i++)            num = (num ^ (1 << i));               document.write(num);    }         let num = 11;      invertBits(num); </script>
4
 
Time complexity : O(log n) Auxiliary space : O(1)
Method 2 (Using Bitset) Here we use the flip() of bitset to invert the bits of the number, in order to avoid flipping the leading zeroes in the binary representation of the number, we have calculated the number of bits in the binary representation and flipped only the actual bits of the number. We have used to_ulong() to convert bitset to number. 
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to invert actual bits// of a number.#include <bits/stdc++.h>using namespace std; void invertBits(int num){    // calculating number of bits    // in the number    int x = log2(num) + 1;     // Considering number to be 32 bit integer;    bitset<32> b(num);     // reversing the bits one by one    for (int i = 0; i < x; i++)        b.flip(i);     // converting bitset to number    cout << b.to_ulong();} // Driver codeint main(){    int num = 11;    invertBits(num);    return 0;}
// Java program to invert actual// bits of a number.class GFG{    static void invertBits(int num)    {        // calculating number of        // bits in the number        int x = (int)(Math.log(num) /                      Math.log(2)) + 1;             // Inverting the bits        // one by one                 for (int i = 0; i < x; i++)        num = (num ^ (1 << i));             System.out.print(num);    }         // Driver code    public static void main(String[] args)    {        int num = 11;        invertBits(num);    }} // This code is contributed by Mukul Singh
# Python 3 program to invert actual# bits of a number.import math def invertBits(num):         # calculating number of    # bits in the number    x = int(math.log(num, 2.0) + 1);     # Inverting the bits    # one by one    for i in range(0, x):        num = (num ^ (1 << i));     print(num); # Driver codenum = 11;invertBits(num); # This code is contributed# by Akanksha Rai
// C# program to invert actual// bits of a number.using System; class GFG{    static void invertBits(int num)    {        // calculating number of        // bits in the number        int x = (int)Math.Log(num, 2) + 1;             // Inverting the bits        // one by one        for (int i = 0; i < x; i++)        num = (num ^ (1 << i));             Console.Write(num);    }         // Driver code    static void Main()    {        int num = 11;        invertBits(num);    } } // This code is contributed by Anuj_67
<?php// PHP program to invert actual// bits of a number.function invertBits($num){    // calculating number of    // bits in the number    $x = log($num) + 1;     // Inverting the bits    // one by one    for ($i = 0; $i < $x; $i++)    $num = ($num ^ (1 << $i));         echo $num;} // Driver code$num = 11;invertBits($num); // This code is contributed// by ajit?>
<script>    // Javascript program to invert actual bits of a number.         function invertBits(num)    {        // calculating number of        // bits in the number        let x = Math.log(num, 2) + 1;               // Inverting the bits        // one by one        for (let i = 0; i < x; i++)        num = (num ^ (1 << i));               document.write(num);    }         let num = 11;      invertBits(num); </script>
4
 
Time complexity: O(log n) Auxiliary space: O(1)
Method 3 (Using bitmask):
Here, we will create a mask by setting all the bits from MSB(including MSB) and then take XOR with the original number
C++
Java
// CPP program to invert actual bits// of a number.#include <bits/stdc++.h>using namespace std; void invertBits(int num){    // calculating the mask    int x = num;     // say num = 100000      x |= x >> 1;    // 100000 | 010000 = 110000      x |= x >> 2;    // 110000 | 001100 = 111100      x |= x >> 4;    // 111100 | 000011 = 111111      x |= x >> 8;    // 111111 | 000000 = 111111      x |= x >> 16;    // 111111 | 000000 = 111111      cout << (num ^ x); // 100000 | 111111 = 011111} // Driver codeint main(){    int num = 11;    invertBits(num);    return 0;}
/*package whatever //do not write package name here */ import java.io.*; class GFG {  public static void invertBits(int num) {    //base case    if(num == 0)    {      System.out.println(1);      return;    }    // calculating the mask    int x = num;     // say num = 100000    x |= x >> 1;    // 100000 | 010000 = 110000    x |= x >> 2;    // 110000 | 001100 = 111100    x |= x >> 4;    // 111100 | 000011 = 111111    x |= x >> 8;    // 111111 | 000000 = 111111    x |= x >> 16;    // 111111 | 000000 = 111111         System.out.println(num ^ x); // 100000 | 111111 = 011111  }  // Driver code    public static void main(String[] args)    {        int num = 11;        invertBits(num);    }} // This code is contributed by lapimpale@
Output:
4
Time complexity: O(1) 
Auxiliary space: O(1)
 
vt_m
jit_t
rituraj_jain
Code_Mech
Akanksha_Rai
divyesh072019
divyeshrabadiya07
kanhaiyanathani8
lapimpale
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Cyclic Redundancy Check and Modulo-2 Division
Binary representation of a given number
Program to find whether a given number is power of 2
Add two numbers without using arithmetic operators
Josephus problem | Set 1 (A O(n) Solution)
Bit Fields in C
Set, Clear and Toggle a given bit of a number in C
Find the element that appears once
Bits manipulation (Important tactics)