The Wayback Machine - https://web.archive.org/web/20241005172233/https://www.geeksforgeeks.org/next-higher-number-with-same-number-of-set-bits/
Open In App

Next higher number with same number of set bits

Last Updated : 29 Oct, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a number x, find next number with same number of 1 bits in it’s binary representation.
For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit machine). It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (100012).
Algorithm:
When we observe the binary sequence from 0 to 2n – 1 (n is # of bits), right most bits (least significant) vary rapidly than left most bits. The idea is to find right most string of 1’s in x, and shift the pattern to right extreme, except the left most bit in the pattern. Shift the left most bit in the pattern (omitted bit) to left part of x by one position. An example makes it more clear, 
 

x = 156

10 
 

x = 10011100

(2) 
 

10011100
00011100 - right most string of 1's in x
00000011 - right shifted pattern except left most bit ------> [A]
00010000 - isolated left most bit of right most 1's pattern
00100000 - shiftleft-ed the isolated bit by one position ------> [B]
10000000 - left part of x, excluding right most 1's pattern ------> [C]
10100000 - add B and C (OR operation) ------> [D]
10100011 - add A and D which is required number 163

(10)
After practicing with few examples, it easy to understand. Use the below given program for generating more sets.
Program Design:
We need to note few facts of binary numbers. The expression x & -x will isolate right most set bit in x (ensuring x will use 2’s complement form for negative numbers). If we add the result to x, right most string of 1’s in x will be reset, and the immediate ‘0’ left to this pattern of 1’s will be set, which is part [B] of above explanation. For example if x = 156, x & -x will result in 00000100, adding this result to x yields 10100000 (see part D). We left with the right shifting part of pattern of 1’s (part A of above explanation).
There are different ways to achieve part A. Right shifting is essentially a division operation. What should be our divisor? Clearly, it should be multiple of 2 (avoids 0.5 error in right shifting), and it should shift the right most 1’s pattern to right extreme. The expression (x & -x) will serve the purpose of divisor. An EX-OR operation between the number X and expression which is used to reset right most bits, will isolate the rightmost 1’s pattern.
A Correction Factor:
Note that we are adding right most set bit to the bit pattern. The addition operation causes a shift in the bit positions. The weight of binary system is 2, one shift causes an increase by a factor of 2. Since the increased number (rightOnesPattern in the code) being used twice, the error propagates twice. The error needs to be corrected. A right shift by 2 positions will correct the result.
The popular name for this program is same number of one bits. 
 

C++




#include<iostream>
 
using namespace std;
 
typedef unsigned int uint_t;
 
// this function returns next higher number with same number of set bits as x.
uint_t snoob(uint_t x)
{
 
  uint_t rightOne;
  uint_t nextHigherOneBit;
  uint_t rightOnesPattern;
 
  uint_t next = 0;
 
  if(x)
  {
 
    // right most set bit
    rightOne = x & -(signed)x;
 
    // reset the pattern and set next higher bit
    // left part of x will be here
    nextHigherOneBit = x + rightOne;
 
    // nextHigherOneBit is now part [D] of the above explanation.
 
    // isolate the pattern
    rightOnesPattern = x ^ nextHigherOneBit;
 
    // right adjust pattern
    rightOnesPattern = (rightOnesPattern)/rightOne;
 
    // correction factor
    rightOnesPattern >>= 2;
 
    // rightOnesPattern is now part [A] of the above explanation.
 
    // integrate new pattern (Add [D] and [A])
    next = nextHigherOneBit | rightOnesPattern;
  }
 
  return next;
}
 
int main()
{
  int x = 156;
  cout<<"Next higher number with same number of set bits is "<<snoob(x);
 
  getchar();
  return 0;
}


Java




// Java Implementation on above approach
class GFG
{
     
// this function returns next higher
// number with same number of set bits as x.
static int snoob(int x)
{
 
int rightOne, nextHigherOneBit, rightOnesPattern, next = 0;
 
if(x > 0)
{
 
    // right most set bit
    rightOne = x & -x;
 
    // reset the pattern and set next higher bit
    // left part of x will be here
    nextHigherOneBit = x + rightOne;
 
    // nextHigherOneBit is now part [D] of the above explanation.
 
    // isolate the pattern
    rightOnesPattern = x ^ nextHigherOneBit;
 
    // right adjust pattern
    rightOnesPattern = (rightOnesPattern)/rightOne;
 
    // correction factor
    rightOnesPattern >>= 2;
 
    // rightOnesPattern is now part [A] of the above explanation.
 
    // integrate new pattern (Add [D] and [A])
    next = nextHigherOneBit | rightOnesPattern;
}
 
return next;
}
 
// Driver code
public static void main (String[] args)
{
    int x = 156;
    System.out.println("Next higher number with same" +
                    "number of set bits is "+snoob(x));
}
}
 
// This code is contributed by mits


Python 3




# This function returns next
# higher number with same
# number of set bits as x.
def snoob(x):
     
    next = 0
    if(x):
         
        # right most set bit
        rightOne = x & -(x)
         
        # reset the pattern and
        # set next higher bit
        # left part of x will
        # be here
        nextHigherOneBit = x + int(rightOne)
         
        # nextHigherOneBit is
        # now part [D] of the
        # above explanation.
        # isolate the pattern
        rightOnesPattern = x ^ int(nextHigherOneBit)
         
        # right adjust pattern
        rightOnesPattern = (int(rightOnesPattern) /
                            int(rightOne))
         
        # correction factor
        rightOnesPattern = int(rightOnesPattern) >> 2
         
        # rightOnesPattern is now part
        # [A] of the above explanation.
         
        # integrate new pattern
        # (Add [D] and [A])
        next = nextHigherOneBit | rightOnesPattern
    return next
 
# Driver Code
x = 156
print("Next higher number with " +
      "same number of set bits is",
                          snoob(x))
 
# This code is contributed by Smita


C#




// C# Implementation on above approach
using System;
class GFG
{
     
// this function returns next higher
// number with same number of set bits as x.
static int snoob(int x)
{
 
    int rightOne, nextHigherOneBit,
        rightOnesPattern, next = 0;
     
    if(x > 0)
    {
     
        // right most set bit
        rightOne = x & -x;
     
        // reset the pattern and set next higher bit
        // left part of x will be here
        nextHigherOneBit = x + rightOne;
     
        // nextHigherOneBit is now part [D]
        // of the above explanation.
     
        // isolate the pattern
        rightOnesPattern = x ^ nextHigherOneBit;
     
        // right adjust pattern
        rightOnesPattern = (rightOnesPattern) / rightOne;
     
        // correction factor
        rightOnesPattern >>= 2;
     
        // rightOnesPattern is now part [A]
        // of the above explanation.
     
        // integrate new pattern (Add [D] and [A])
        next = nextHigherOneBit | rightOnesPattern;
    }
    return next;
}
 
// Driver code
static void Main()
{
    int x = 156;
    Console.WriteLine("Next higher number with same" +
                      "number of set bits is " + snoob(x));
}
}
 
// This code is contributed by mits


PHP




<?php
 
// This function returns next higher number
// with same number of set bits as x.
function snoob($x)
{
    $next = 0;
     
    if($x)
    {
     
        // right most set bit
        $rightOne = $x & - $x;
     
        // reset the pattern and set next higher
        // bit left part of x will be here
        $nextHigherOneBit = $x + $rightOne;
     
        // nextHigherOneBit is now part [D] of
        // the above explanation.
     
        // isolate the pattern
        $rightOnesPattern = $x ^ $nextHigherOneBit;
     
        // right adjust pattern
        $rightOnesPattern = intval(($rightOnesPattern) /
                                            $rightOne);
     
        // correction factor
        $rightOnesPattern >>= 2;
     
        // rightOnesPattern is now part [A]
        // of the above explanation.
     
        // integrate new pattern (Add [D] and [A])
        $next = $nextHigherOneBit | $rightOnesPattern;
    }
 
    return $next;
}
 
// Driver Code
$x = 156;
echo "Next higher number with same " .
     "number of set bits is " . snoob($x);
 
// This code is contributed by ita_c
?>


Javascript




<script>
 
    // this function returns next higher 
    // number with same number of set bits as x.
    function snoob(x)
    {
        let rightOne, nextHigherOneBit, rightOnesPattern, next = 0;
        if(x > 0)
        {
            // right most set bit
            rightOne = x & -x;
           
            // reset the pattern and set next higher bit
            // left part of x will be here
            nextHigherOneBit = x + rightOne;
           
            // nextHigherOneBit is now part [D] of the above explanation.
           
            // isolate the pattern
            rightOnesPattern = x ^ nextHigherOneBit;
           
            // right adjust pattern
            rightOnesPattern = (rightOnesPattern)/rightOne;
           
            // correction factor
            rightOnesPattern >>= 2;
           
            // rightOnesPattern is now part [A] of the above explanation.
           
            // integrate new pattern (Add [D] and [A])
            next = nextHigherOneBit | rightOnesPattern;
        }
        return next;
    }
     
    // Driver code
    let x = 156;
    document.write("Next higher number with same " +
                     "number of set bits is "+snoob(x));
     
    // This code is contributed by avanitrachhadiya2155
     
</script>


Output: 

Next higher number with same number of set bits is 163

Time Complexity: O(1)

Auxiliary Space: O(1)

Usage: Finding/Generating subsets.
Variations: 
 

  1. Write a program to find a number immediately smaller than given, with same number of logic 1 bits? (Pretty simple)
  2. How to count or generate the subsets available in the given set?

References: 
 

  1. A nice presentation here.
  2. Hackers Delight by Warren (An excellent and short book on various bit magic algorithms, a must for enthusiasts)
  3. C A Reference Manual by Harbison and Steele (A good book on standard C, you can access code part of this post here).

– Venki.
 



Previous Article
Next Article

Similar Reads

Next higher palindromic number using the same set of digits
Given a palindromic number num having n number of digits. The problem is to find the smallest palindromic number greater than num using the same set of digits as in num. If no such number can be formed then print "Not Possible". The number could be very large and may or may not even fit into long long int. Examples: Input : 4697557964Output : 47569
15+ min read
Closest (or Next) smaller and greater numbers with same number of set bits
Given a positive integer n, print the next smallest and the previous largest number that has the same number of 1 bit in their binary representation. Examples: Input : n = 5 Output : Closest Greater = 6 Closest Smaller = 3 Note that 5, 6 and 3 have same number of set bits. Input : n = 11 Output : Closest Greater = 13 Closest Smaller = 7 The Brute F
15+ min read
Next higher number using atmost one swap operation
Given a non-negative number num. The problem is to find the smallest number greater than num by performing atmost on swap operation between any two digits in num. If no larger number can be formed then print "Not Possible".The number could be very large and may not even fit into long long int. Examples: Input : num = "218765"Output : 258761Explanat
11 min read
Point to next higher value node in a linked list with an arbitrary pointer
Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all nodes one by one, for every node, find the node whi
15+ min read
Javascript Program For Pointing To Next Higher Value Node In A Linked List With An Arbitrary Pointer
Given singly linked list with every node having an additional "arbitrary" pointer that currently points to NULL. Need to make the "arbitrary" pointer point to the next higher-value node. We strongly recommend to minimize your browser and try this yourself first A Simple Solution is to traverse all nodes one by one, for every node, find the node whi
4 min read
Check if all bits can be made same by flipping two consecutive bits
Given a binary string, the task is to find whether all the digits of the string can be made equal i.e either 0 or 1 by flipping two consecutive bits any number of times.Examples: Input: 01011Output: YESExplanation:Flip 2nd and 3rd bit -> 00111, again flipping 1'st and 2'nd bit -> 11111 Input: 100011Output: NOExplanation:No number of moves can
5 min read
Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X & Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X & Y) = M, where ⊕ denotes the Bitwise XOR and & denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n > 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Check if a number has same number of set and unset bits
Given a number N, the task is to check whether the count of the set and unset bits in the given number are same. Examples: Input: 12Output: Yes1100 is the binary representation of 12which has 2 set and 2 unset bits Input: 14Output: No Approach: Traverse in the binary representation of the given number, check if the leftmost bit is set or not using
5 min read
Maximum number of contiguous array elements with same number of set bits
Given an array with n elements. The task is to find the maximum number of contiguous array elements which have the same number of set bits. Examples: Input : arr[] = {14, 1, 2, 32, 12, 10} Output : 3 Elements 1, 2, 32 have same number of set bits and are contiguous. Input : arr[] = {1, 6, 9, 15, 8} Output : 2 Elements 6, 9 have same number of set b
6 min read
Flip bits of the sum of count of set bits of two given numbers
Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representation of the sum obtained = 101Flipping the bits of th
5 min read
Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most N/2. Examples: Input: S = "1010001"Output: 3Expla
12 min read
Print numbers having first and last bits as the only set bits
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.Examples: Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2 Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i. C
10 min read
Next greater integer having one more number of set bits
Given a positive integer 'n' having 'x' number of set bits in its binary representation. The problem is to find the next greater integer(smallest integer greater than n), having (x+1) number of set bits in its binary representation.Examples : Input : 10 Output : 11 (10)10 = (1010)2 is having 2 set bits. (11)10 = (1011)2 is having 3 set bits and is
6 min read
Rearrange given Array such that all set bit positions have higher value than others
Given an array B1[] and a binary array B2[] each of size N, the task is to rearrange array B1[] in a way such that for all setbit position i of B2[] the value of B1[i] will be greater than the values where bit is not set in B2[] i.e for all (i, j) B1[i] > B1[j] when B2[i] = 1, B2[j] = 0 (0 ≤ i, j < N). Note: If multiple arrangements are possi
13 min read
Toggle bits of a number except first and last bits
Given a number, the task is to toggle bits of the number except the first and the last bit.Examples: Input : 10 Output : 12 Binary representation:- 1 0 1 0 After toggling first and last : 1 1 0 0 Input : 9 Output : 15 Binary representation : 1 0 0 1 After toggling first and last : 1 1 1 1 Prerequisite: Find most significant set bit of a number Gene
8 min read
Same Number Of Set Bits As N
Given a positive integer N, find out how many positive integers strictly less than N have the same number of set bits as N. Examples: Input : 8 Output :3 Explanation: Binary representation of 8 : 1000, so number of set bits in 8 is 1. So the integers less than 8 with same number of set bits are : 4, 2, 1 Input :1 Output :0 Input :4 Output :2 Approa
9 min read
Maximum sum by adding numbers with same number of set bits
Given an array of N numbers, the task is to find the maximum sum that can be obtained by adding numbers with the same number of set bits. Examples: Input: 32 3 7 5 27 28 Output: 34Input: 2 3 8 5 6 7 Output: 14 Approach: Traverse in the array and count the number of set bits for every element.Initialize an array for 32 bits, assuming the number to h
8 min read
Count of pairs in an Array with same number of set bits
Given an array arr containing N integers, the task is to count the possible number of pairs of elements with the same number of set bits. Examples: Input: N = 8, arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 9 Explanation: Elements with 1 set bit: 1, 2, 4, 8 Elements with 2 set bits: 3, 5, 6 Elements with 3 set bits: 7 Hence, {1, 2}, {1, 4}, {1, 8}, {2,
7 min read
Find next greater number with same set of digits
Given a number N as string, find the smallest number that has same set of digits as N and is greater than N. If N is the greatest possible number with its set of digits, then print "Not Possible". Examples: Input: N = "218765"Output: "251678"Explanation: The next number greater than 218765 with same set of digits is 251678. Input: n = "1234"Output:
9 min read
Check if Array has 2 distinct subsequences where smaller one has higher Sum
Given an array A[] of N integers. Check if there exist 2 distinct sub-sequences X and Y of the given array, such that the sum of elements of X is greater than the sum of elements of Y, but the number of elements in X is less than the number of elements in Y. Examples: Input: N = 5, A[] = {2, 3, 8, 1, 6}Output: YESExplanation: Consider the sequences
15 min read
Binary representation of next greater number with same number of 1's and 0's
Given a binary input that represents binary representation of positive number n, find binary representation of smallest number greater than n with same number of 1's and 0's as in binary representation of n. If no such number can be formed, print "no greater number".The binary input may be and may not fit even in unsigned long long int. Examples: I
12 min read
Lexicographically next greater string using same character set
Given a number K and a string S, We have to Find the lexicographically smallest string str of length K such that it's set of letters is a subset of the set of letters of S and S is lexicographically smaller than str. Examples: Input :k = 3 s = zbf Output: zbz Explanation: zbz is greater than zbf and it is smaller than any other lexicographically gr
8 min read
Find Bit whose minimum sequence flips makes all bits same
Given a binary string consisting only of 1's and 0's. Find the bit (output is either 1 or 0)whose minimum number of contiguous sequence flips can make all bits of the string same.Here, contiguous sequence flip means flipping a substring or 0s or 1s. For Example, in the string "00011110001110", in one flip we can change the string to "11111110001110
6 min read
Find all even length binary sequences with same sum of first and second half bits | Iterative
Given a number N, find all binary sequences of length 2*N such that sum of first N bits is same as the sum of last N bits.Examples: Input: N = 2 Output: 0000 0101 0110 1001 1010 1111 Input: N = 1 Output: 00 11 Note: The recursive approach to this problem can be found here. Approach: A simple approach to run a loop from 0 to 22*N and convert into th
9 min read
Minimize product of first N - 1 natural numbers by swapping same positioned bits of pairs
Given an integer N, the task is to find the minimum positive product of first N - 1 natural numbers, i.e. [1, (N - 1)], by swapping any ith bit of any two numbers any number of times. Note: N is always a perfect power of 2. Since the product can be very large, print the answer modulo 109 + 7. Examples: Input: N = 4Output: 6Explanation:No swapping o
6 min read
Find all even length binary sequences with same sum of first and second half bits
Given a number n, find all binary sequences of length 2n such that sum of first n bits is same as sum of last n bits.Examples: Input: N = 2 Output: 0101 1111 1001 0110 0000 1010 Input: N = 3 Output: 011011 001001 011101 010001 101011 111111 110011 101101 100001 110101 001010 011110 010010 001100 000000 010100 101110 100010 110110 100100 The idea is
15+ min read
Check if all bits can be made same by single flip
Given a binary string, find if it is possible to make all its digits equal (either all 0's or all 1's) by flipping exactly one bit. Input: 101Output: YeExplanation: In 101, the 0 can be flipped to make it all 1 Input: 11Output: NoExplanation: No matter whichever digit you flip, you will not get the desired string. Input: 1Output: YesExplanation: We
5 min read
Count even length binary sequences with same sum of first and second half bits
Given a number n, find count of all binary sequences of length 2n such that sum of first n bits is same as sum of last n bits. Examples: Input: n = 1Output: 2There are 2 sequences of length 2*n, thesequences are 00 and 11Input: n = 2Output: 6There are 6 sequences of length 2*n, thesequences are 0101, 0110, 1010, 1001, 0000and 1111The idea is to fix
15+ min read
Next greater Number than N with the same quantity of digits A and B
Given a number [Tex]N [/Tex]and two digits [Tex]A [/Tex]and [Tex]B [/Tex]. The task is to find the least number not less than N which contains the equal number of digits A and B.Note: N <= 107Examples: Input : N = 4500, A = 4, B = 7 Output : 4747 The number greater than 4500 which has the same quantity of number '4' and number '7' is 4747.Input
7 min read
Article Tags :
Practice Tags :