
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if Bits are Alternating in Integer using JavaScript
Problem
We are required to write a JavaScript function that takes in an integer, num, as the first and the only argument.
Our function should check whether the binary representation of num has alternating bits − namely, if two adjacent bits will always have different values.
For example, if the input to the function is
Input
const num = 5;
Output
const output = true;
Output Explanation
Because the binary form of 5 is 101 which have alternating bits.
Example
Following is the code −
const num = 5; const isAlternating = (num = 1) => { const binary = num.toString(2); let curr = binary[0]; for(let i = 1; i < binary.length; i++){ const el = binary[i]; if(curr !== el){ curr = el; continue; }; return false; }; return true; }; console.log(isAlternating(num));
Output
true
Advertisements