Javascript Number twos(n)
function nzero(n, flag) { let zeros = ''; const ch = flag ? '0' : '1'; while (n-- > 0) { zeros += ch;/*w w w .ja v a 2s . co m*/ } return zeros; } Number.prototype.twos = function twos(n) { const zeros = nzero(n, this > 0); return `${zeros}${Math.abs(this).toString(2)}`.substr(-n); };
Number.prototype.twos = function(n) { let c = this < 0 ? '1' : '0'; return ((this < 0 ? '1' : '') + Math.abs(this).toString(2)).pad(c, n).slice(-n); }
Number.prototype.twos = function(n) { var bin = Math.abs(this.valueOf()).toString(2), isNegative = (this.valueOf() < 0); if(bin.length > n) return bin; if(isNegative)//from www. ja v a 2 s.c o m while(bin.length < n) bin = '1'+bin; else while(bin.length < n) bin = '0'+bin; return bin; }
// I feel like this might be the solution: // ((this & (2 ** n - 1)) & this) // but it also requires left padding with zeros, // which feels wrong, so I might as well just do something // else. Unsure if there's a binary trick I don't know. Number.prototype.twos = function (n) { // return (this < 0 ? '1' : '0') + Math.abs(this).toString(2).slice(n * -1 + 1) const compliment = ((this & (2 ** n - 1)) & this) return ('0'.repeat(32) + compliment.toString(2)).slice(-n) }
Number.prototype.twos = function(n) { //You may assume for this excercise that n >= 2... let bits = this.toString(2); let pad = '0'; let neg = bits[0] === '-' ? true : false; if (neg) {//from w w w .j a va 2 s. c o m bits = bits.substring(1); pad = '1'; } while (bits.length < n) bits = pad + bits; return bits; }
//http://www.codewars.com/kata/523fba59cb9aaaef4f000135/train/javascript Number.prototype.twos = function(n) { //You may assume for this excercise that n >= 2... var work = this.toString(2); var work2 = "" var result;/*from w w w .j av a 2 s . c o m*/ for (var i = 0; i < work.length; i++){ if (work[i] === "-"){ work2 += "1"; } else { work2 += work[i]; } } if (work2.length >= n){ return work2.slice(work2.length-n, work2.length); } else { if (work[0] === "-"){ while (work2.length < n){ work2 = "1" + work2; } } else { while (work2.length < n){ work2 = "0" + work2; } } return work2; } }