在 JavaScript 中顛倒一個十進位制數字的位並返回新的十進位制數字
問題
我們需要編寫一個 JavaScript 函式,該函式輸入一個十進位制數字,將其轉換為二進位制並將其 1 位反轉為 0,將 0 反轉為 1,並返回由此形成的新二進位制數的十進位制等效值。
範例
以下是程式碼 −
const num = 45657;
const reverseBitsAndConvert = (num = 1) => {
const binary = num.toString(2);
let newBinary = '';
for(let i = 0; i < binary.length; i++){
const bit = binary[i];
newBinary += bit === '1' ? '0' : 1;
};
const decimal = parseInt(newBinary, 2);
return decimal;
};
console.log(reverseBitsAndConvert(num));輸出
19878
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
JavaScript
PHP