整型位元是否在使用 JavaScript 交替?
問題
要求我們編寫一個 JavaScript 函式,該函式接受一個整數 num 作為第一個且唯一的引數。
我們的函式應該檢查 num 的二進位制表示形式是否有交替位 - 即,相鄰的兩個位總是具有不同的值。
例如,如果輸入函式時為
輸入
const num = 5;
輸出
const output = true;
輸出說明
因為 5 的二進位制形式是 101,具有交替位。
示例
以下是程式碼 -
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));輸出
true
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP