w3resource

JavaScript: Reverse a Binary string

JavaScript String: Exercise-19 with Solution

Reverse Binary Representation

Write a JavaScript function that takes a positive integer and reverses the binary representation of that integer. Finally return the decimal version of the binary string.
Test Data:
(100) -> 19
Explanation:
Binary representation of 100 is 1100100
Reverse of 1100100 is 10011
Decimal form of 10011 is 19
(1134) -> 945
Explanation:
Binary representation of 1134 is 10001101110
Reverse of 10001101110 is 1110110001
Decimal form of 1110110001 is 945

Sample Solution:

JavaScript Code:

function test(n) {
	return parseInt(n.toString(2).split('').reverse().join(''), 2);
}
console.log(test(100));
console.log(test(1134));

Output:

19
945

Explanation:

In the exercise above,

  • The function takes an integer 'n' as input.
  • It converts the integer n to its binary representation using the "toString(2)" method, which returns a string containing the binary representation of the number.
  • It splits the binary string into an array of characters, reverses the order of the characters, and then joins them back into a single string using the "reverse()" and "join('')" methods.
  • Finally, it converts the reversed binary string back to an integer using "parseInt(string, 2)", where the second argument specifies that the string is in base 2 (binary).
  • The function returns a reversed binary integer.
  • The function is tested with different input numbers, and the results are printed to the console.

Flowchart:

Flowchart: JavaScript: Longest Palindromic Subsequence

Live Demo:

See the Pen javascript-string-exercise-64 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that converts a positive integer to its binary string, reverses it, and converts it back to decimal.
  • Write a JavaScript function that handles leading zeros in the binary representation before reversal.
  • Write a JavaScript function that validates the input number and returns an error for non-positive integers.
  • Write a JavaScript function that compares the original and reversed binary values for verification.

Go to:


PREV : Count Substring Occurrences.
NEXT : Pad String to Length.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.