Given a binary input that represents a binary representation of the positive number n, find a binary representation of n+1. We will try to find out this with the different approaches discussed below.
Examples:
Input : 10011
Output : 10100
Here n = (19)10 = (10011)2
next greater integer = (20)10 = (10100)2
Table of Content
Approach 1: Naive Approach
- Input is stored as a string to handle large numbers.
- Traverse the string from right to left.
- Convert consecutive 1s to 0s until the first 0 is found.
- Replace that 0 with 1. If no 0 is found, append 1 to the string.
Example: Below is the implementation of the above approach
function nextGreater(num) {
let i = num.length - 1;
while (i >= 0) {
if (num[i] === '0' ) {
num =
num.substring(0, i) +
'1' + num.substring(i + 1);
break ;
} else {
num =
num.substring(0, i) +
'0' + num.substring(i + 1);
}
i--;
}
if (i < 0) {
num = '1' + num;
}
return num;
} // Driver program to test above let num = '1101' ;
console.log( "Binary representation of next number = " +
nextGreater(num)
); |
Binary representation of next number = 1110
Approach 2: Optimised Approach
Convert the binary string num to an integer using the bitset class and its to_ulong method to obtain the integer representation.
Increment the integer by 1 to find the next greater integer.
Convert the incremented integer back to a binary string using the bitset class and its to_string method.
- Remove any leading zeros from the resulting binary string using string manipulation methods like erase and find_first_not_of, and then return the modified binary string.
Example: Below is the implementation of the above approach
// JavaScript Code for the above approach function nextGreater(num) {
// Convert binary string to integer
const n = parseInt(num, 2);
// Increment integer by 1
const nextNum = n + 1;
// Convert integer back to binary string
let result = nextNum.toString(2);
// Remove leading zeros
result = result.replace(/^0+/, '' );
return result;
} // Driver code const num = "110011" ;
console.log( "Binary representation of next number =" , nextGreater(num));
|
Binary representation of next number = 110100