- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Are bits 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
To Continue Learning Please Login
Login with Google