Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • 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:
Reverse actual bits of the given number
Next article icon

Reverse actual bits of the given number

Last Updated : 25 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a non-negative integer n, the task is to reverse the bits in its binary representation and return the resulting decimal number. The reversal should consider only the actual binary digits without any leading zeros.

Examples : 

Input : 11
Output : 13
Explanation: (11)10 = (1011)2.
After reversing the bits we get: (1101)2 = (13)10.

Input : 10
Output : 5
Explanation : (10)10 = (1010)2.
After reversing the bits we get: (0101)2 = (101)2 = (5)10.

Approach:

 The idea is to build the reversed number by examining each bit of the input number from right to left, while simultaneously constructing the result from left to right using left shift and right shift operators.

Step by step approach:

  1. Traverse each bit of the input number using right shift operations (n >>= 1).
  2. Build the result by shifting it left (ans <<= 1) before each new bit is processed.
  3. When a '1' bit is encountered in the input (n & 1 == 1), set the rightmost bit of the result (ans |= 1).
  4. Continue this process until all bits in the input number have been processed (n > 0).

C++
// C++ program to reverse actual bits of a given number #include <iostream> using namespace std;  int reverseBits(unsigned int n) { 	int ans = 0;  	// traversing bits of 'n' from the right 	while (n > 0) { 	     		// bitwise left shift 		// 'ans' by 1 		ans <<= 1;  		// if current bit is '1' 		if (n & 1 == 1) 			ans |= 1;  		// bitwise right shift 		// 'n' by 1 		n >>= 1;  	}  	// required number 	return ans; }  int main() {     int n = 11;     cout << reverseBits(n);     return 0; } 
Java
// Java program to reverse actual bits of a given number  class GfG {      static int reverseBits(int n) {         int ans = 0;          // traversing bits of 'n' from the right         while (n > 0) {                          // bitwise left shift             // 'ans' by 1             ans <<= 1;              // if current bit is '1'             if ((n & 1) == 1)                 ans |= 1;              // bitwise right shift             // 'n' by 1             n >>= 1;         }          // required number         return ans;     }      public static void main(String[] args) {         int n = 11;         System.out.println(reverseBits(n));     } } 
Python
# Python program to reverse actual bits of a given number  def reverseBits(n):     ans = 0      # traversing bits of 'n' from the right     while n > 0:                  # bitwise left shift         # 'ans' by 1         ans <<= 1          # if current bit is '1'         if (n & 1) == 1:             ans |= 1          # bitwise right shift         # 'n' by 1         n >>= 1      # required number     return ans  if __name__ == "__main__":     n = 11     print(reverseBits(n)) 
C#
// C# program to reverse actual bits of a given number using System;  class GfG {      static uint reverseBits(uint n) {         uint ans = 0;          // traversing bits of 'n' from the right         while (n > 0) {                          // bitwise left shift             // 'ans' by 1             ans <<= 1;              // if current bit is '1'             if ((n & 1) == 1)                 ans |= 1;              // bitwise right shift             // 'n' by 1             n >>= 1;         }          // required number         return ans;     }      static void Main() {         uint n = 11;         Console.WriteLine(reverseBits(n));     } } 
JavaScript
// JavaScript program to reverse actual bits of a given number  function reverseBits(n) {     let ans = 0;      // traversing bits of 'n' from the right     while (n > 0) {                  // bitwise left shift         // 'ans' by 1         ans <<= 1;          // if current bit is '1'         if ((n & 1) === 1)             ans |= 1;          // bitwise right shift         // 'n' by 1         n >>= 1;     }      // required number     return ans; }  let n = 11; console.log(reverseBits(n)); 

Output
13

Time Complexity: O(1)
Space Complexity: O(1)


Next Article
Reverse actual bits of the given number

A

ayushjauhari14
Improve
Article Tags :
  • Bit Magic
  • DSA
  • Reverse
Practice Tags :
  • Bit Magic
  • Reverse

Similar Reads

    Set all the bits in given range of a number
    Given a non-negative number n and two values l and r. The problem is to set the bits in the range l to r in the binary representation of n, i.e, to unset bits from the rightmost lth bit to the rightmost r-th bit. Constraint: 1 <= l <= r <= number of bits in the binary representation of n.Ex
    5 min read
    Set the K-th bit of a given number
    Given a number n and a value k. From the right, set the kth bit in the binary representation of n. The position of LSB(or last bit) is 0, second last bit is 1 and so on. Also, 0 <= k < x, where x is the number of bits in the binary representation of n.Examples: Input : n = 10, k = 2 Output : 1
    4 min read
    Invert actual bits of a number
    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 : 11Output : 4(11)1
    13 min read
    Binary representation of a given number
    Given an integer n, the task is to print the binary representation of the number. Note: The given number will be maximum of 32 bits, so append 0's to the left if the result string is smaller than 30 length.Examples: Input: n = 2Output: 00000000000000000000000000000010Input: n = 0Output: 000000000000
    6 min read
    Write an Efficient C Program to Reverse Bits of a Number
    Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Input : n = 1Output : 2147483648 Explanation : On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648Output : 1 Recommended PracticeReverse BitsTry It!Method1 -
    6 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