04(June) Binary representation of next number
04. Binary Representation of Next Number
The problem can be found at the following link: Question Link
Problem Description
Given a binary representation in the form of a string s of a number n, the task is to find the binary representation of n + 1.
Example:
Input:
s = "10"Output:
11Explanation: "10" is the binary representation of 2, and the binary representation of 3 is "11".
Input:
s = "111"Output:
1000Explanation: "111" is the binary representation of 7, and the binary representation of 8 is "1000".
Approach
Initialization:
Remove leading zeros from the string
s.If
sbecomes empty after removing leading zeros, setsto "0".
Binary Addition:
Convert the string
sto a character array for easier manipulation.Iterate from the last character to the first, simulating binary addition with a carry.
If a '0' is found, change it to '1' and stop the carry.
If a '1' is found, change it to '0' and continue the carry.
If the carry is still present after the loop, prepend '1' to the string.
Return:
Convert the character array back to a string and return it.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
nis the length of the strings, as we iterate through the string once.Expected Auxiliary Space Complexity: O(n), as we store the resultant string in a character array of size
n.
Code
C++
Java
Python
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated