0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

js フェイクバイナリの変換

Posted at

##お題
引数で与えられた数字0~4は0、5~9は1に変換して返す。

function fakeBin(x){
//write your code.
}

##出力結果 例

fakeBin('45385593107843568')// 01011110001100111
fakeBin('509321967506747')//101000111101101 
fakeBin('366058562030849490134388085')//011011110000101010000011011

##使ったもの
for文
if文

##考え方
・変換後の数字を入れる配列を用意する
・for文で引数の数字を順番に条件分岐で変換する
・用意した配列を返しておわり

##コード

function fakeBin(str){
  var newStr = "";
  for(var i=0;i<str.length;i++){
    if(Number(str[i])>=5){
      newStr += "1"
    }
    else{
      newStr += "0";
    }
  }
  return newStr;
}

##例外処理

'use strict';
function fakeBin(str){
  var newStr = "";
  if(isNaN(str) === false){
  for(var i=0;i<str.length;i++){
    if(Number(str[i])>=5){
      newStr += "1"
    }
    else{
      newStr += "0";
    }
  }
  return newStr;
 }else{
  throw "TypeError:"+ str + " is not a number.";
 }
}
fakeBin("a");

##ES6

function fakeBin(x) {
    return x.split('').map(n => n < 5 ? 0 : 1).join('');
}
const fakeBin=x=>[...x].map(n => n < 5 ? 0 : 1).join('');

###他にもコードが浮かんだ方、コメントお待ちしております

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?