
- 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
Circular Permutation in Binary Representation in C++
Suppose we have 2 integers n and start. Our task is return any permutation p of (0,1,2.....,2^n -1) as follows −
- p[0] = start
- p[i] and p[i+1] differ by only one bit in their binary representation.
- p[0] and p[2^n -1] must also differ by only one bit in their binary representation.
So if the input is like n = 2 and start = 3, then the returned array will be [3,2,0,1], these are [11,10,00,01]
To solve this, we will follow these steps −
- ans is an array
- for i in range 0 to 2^n
- insert start XOR i XOR i/2 into ans
- return ans
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> circularPermutation(int n, int start) { vector <int> ans; for(int i = 0 ; i < 1<<n; i++){ ans.push_back(start ^ i ^(i>>1)); } return ans; } }; main(){ Solution ob; print_vector(ob.circularPermutation(5,3)); }
Input
5 3
Output
[3, 2, 0, 1, 5, 4, 6, 7, 15, 14, 12, 13, 9, 8, 10, 11, 27, 26, 24, 25, 29, 28, 30, 31, 23, 22, 20, 21, 17, 16, 18, 19, ]
- Related Articles
- Binary Tree Representation in Data Structures
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Binary representation of a given number in C++
- Calculating 1s in binary representation of numbers in JavaScript
- Array Representation Of Binary Heap
- Prime Number of Set Bits in Binary Representation in C++
- Prime Number of Set Bits in Binary Representation in Python
- XOR counts of 0s and 1s in binary representation in C++
- Count numbers have all 1s together in binary representation in C++
- Find value of k-th bit in binary representation in C++
- Check if binary representation of a number is palindrome in Python
- Sorting according to number of 1s in binary representation using JavaScript
- Maximum 0’s between two immediate 1’s in binary representation in C++
- Number of leading zeros in binary representation of a given number in C++

Advertisements