將字串轉換成二進位制字串 - JavaScript
我們需要編寫一個 JavaScript 函式,該函式接收一個帶有小寫字母的字串,並返回一個新字串,其中 [a, m] 之間的所有元素均由 0 表示,而 [n, z] 之間的所有元素均由 1 表示。
示例
以下是程式碼示例 −
const str = 'Hello worlld how are you';
const stringToBinary = (str = '') => {
const s = str.toLowerCase();
let res = '';
for(let i = 0; i < s.length; i++){
// for special characters
if(s[i].toLowerCase() === s[i].toUpperCase()){
res += s[i];
continue;
};
if(s[i] > 'm'){
res += 1;
}else{
res += 0;
};
};
return res;
};
console.log(stringToBinary(str));輸出
以下是在控制檯中的輸出 −
00001 111000 011 010 111
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP