VOOZH about

URL: https://www.geeksforgeeks.org/dsa/binary-representation-of-next-number/

⇱ Binary representation of next number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Binary representation of next number

Last Updated : 28 Apr, 2025

Given a binary string that represents binary representation of positive number n, the task is to find the binary representation of n+1. The binary input may or may not fit in an integer, so we need to return a string.

Examples:

Input: s = "10011"
Output: "10100"
Explanation:
Here n = (19)10 = (10011)2
next greater integer = (20)10 = (10100)2

Input: s = "111011101001111111"
Output: "111011101010000000"

Approach:

The idea is to use the binary counting pattern where incrementing a number requires turning all trailing 1s to 0s and then changing the rightmost 0 to 1 (or adding a new leading 1 if all digits are 1s). This approach directly simulates the carry operation of binary addition without converting to decimal.

Step by step approach:

  1. Remove any leading zeros as they don't affect the number's value.
  2. Scan from right to left (least significant bit to most significant bit).
    • Change all consecutive 1s from right to 0s until finding a 0.
    • Change the first encountered 0 to 1 and stop the process.
  3. If no 0 is found (all bits are 1), prepend a new leading 1 and set all other bits to 0.

Output
10100

Time Complexity: O(n), where n is the length of string. The input string is traversed at most 3 times.
Auxiliary Space: O(n), due to substring.

Comment