![]() |
VOOZH | about |
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)2Input: 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:
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.