Binary representation of next greater number with same number of 1's and 0's in C Program?

In C programming, finding the binary representation of the next greater number with the same number of 1's and 0's is a classic problem that can be solved using a next-permutation approach. Given a binary string, we need to find the smallest binary number that is greater than the given number and contains exactly the same count of 0's and 1's.

Syntax

char* nextBinary(char* bin);

Algorithm

The algorithm works in two main steps −

  1. Find the rightmost '01' pattern and swap it to '10'
  2. Rearrange all bits after the swap position to get the smallest possible number

Example

Here's a complete C implementation that finds the next greater binary number −

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void swap(char *a, char *b) {
    char temp = *a;
    *a = *b;
    *b = temp;
}

char* nextBinary(char* bin) {
    int len = strlen(bin);
    int i;
    
    // Find rightmost '01' pattern
    for (i = len - 2; i >= 0; i--) {
        if (bin[i] == '0' && bin[i + 1] == '1') {
            swap(&bin[i], &bin[i + 1]);
            break;
        }
    }
    
    // If no '01' pattern found, no greater number exists
    if (i == -1) {
        return "No greater number possible";
    }
    
    // Rearrange bits after position i+1 to get smallest number
    int j = i + 2, k = len - 1;
    while (j < k) {
        if (bin[j] == '1' && bin[k] == '0') {
            swap(&bin[j], &bin[k]);
            j++;
            k--;
        } else if (bin[j] == '0') {
            j++;
        } else {
            k--;
        }
    }
    
    return bin;
}

int main() {
    char bin[] = "1011";
    printf("Original binary: %s<br>", bin);
    char* result = nextBinary(bin);
    printf("Next greater binary: %s<br>", result);
    
    return 0;
}
Original binary: 1011
Next greater binary: 1101

How It Works

For the input "1011" −

  1. Find rightmost '01' at positions 1-2, swap to get "1101"
  2. Since there are no more bits after position 2, we're done
  3. The result "1101" (13 in decimal) is the next greater number than "1011" (11 in decimal)

Key Points

  • The algorithm maintains the same count of 0's and 1's
  • Time complexity is O(n) where n is the length of binary string
  • Space complexity is O(1) as we modify the string in place
  • If no '01' pattern exists, no greater number is possible

Conclusion

This approach efficiently finds the next greater binary number with the same bit count by using a two-step process: finding the rightmost '01' pattern and rearranging subsequent bits for the minimal result.

Updated on: 2026-03-15T11:48:52+05:30

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements