Open In App

Binary Representation of Previous Number in JavaScript

Last Updated : 17 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a binary input of a positive number, our task is to find the binary representation of a number that is one less than a given binary number n in JavaScript.

Example:

Input: 100010
Output: 100001
Explanation: The decimal of 100010 is 34 and 100001 is 33.

Approach

  • The function "previousBinary1" converts the input binary string to a decimal number using "parseInt(binary, 2)".
  • It subtracts 1 from the decimal value to find the previous number.
  • The function converts the resulting decimal number back to a binary string using "toString(2)".
  • The resulting binary string, which represents the previous number, is returned by the function.
  • The function call console.log(previousBinary1('100010')) prints the previous binary number, resulting in '100001'.

Example: The example below shows how to Find the binary representation of previous number using Brute Force Approach.

JavaScript
function previousBinary1(binary) {
    
    // Parse Binary to Decimal
    const decimal = parseInt(binary, 2);
    
    // Subtract 1
    const previousDecimal = decimal - 1;
    
    // Convert Back to Binary
    const previousBinary = previousDecimal.toString(2);
    
    return previousBinary;
}

console.log(previousBinary1('100010')); 

Output
100001

Time Complexity: O(n)

Space Complexity: O(log M)


Next Article

Similar Reads