Open In App

JavaScript Program for Binary Representation of Next Number

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

Approach 1: Naive Approach

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)
);

Output
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.

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));

Output
Binary representation of next number = 110100

Article Tags :