javascript - How to reverse bitwise shift? - javascript

This is my Function. In this function there is two parameter value and how many bits shift.
function test(Value, ShiftBits) {
return (Value << ShiftBits) | (Value >>> (32 - ShiftBits));
};
Now i want to make reverse of this function. In this test() function if i put
test(105748,7);
it returns 13535744;
Now i need to make a function like, if i put
rev_test(13535744,7);
it returns 105748;
Any help Appreciated.

Why not reverse the logic? I spelled it out below:
Number.prototype.zeroFillBin = function() {
var s = this.toString(2);
while (s.length < 32) s = '0' + s;
return s;
}
function test(val, bits) {
return (val << bits) | (val >>> (32 - bits));
};
function rev_test(val, bits) {
return (val >>> bits) | (val << (32 - bits));
};
x = 105748;
y = test(x, 7); // return 13535744
console.log(x + ' = ' + x.zeroFillBin())
console.log(y + ' = ' + y.zeroFillBin() + '\n');
x = 13535744;
y = rev_test(x, 7); // return 105748
console.log(x + ' = ' + x.zeroFillBin())
console.log(y + ' = ' + y.zeroFillBin() + '\n');
Results:
105748 = 00000000000000011001110100010100
13535744 = 00000000110011101000101000000000
13535744 = 00000000110011101000101000000000
105748 = 00000000000000011001110100010100

105748 << 1 // 13535744
13535744 >> 1 // 105748

Related

How to make triangle with '&' and '+' symbol in JavaScript?

How to make a pyramid like this one in javascript?
👇
&
+++
&&&&&
+++++++
I've tried this one but didn't get the exact output.
function pyramid(n) {
for (let i = 1; i <= n; i++) {
let str = ' '.repeat(n - i);
let symb1 = '&'.repeat(i * 2 - 1);
let symb2 = '+'.repeat(i * 2 - 1);
console.log(str + symb1 + str);
console.log(str + symb2 + str);
}
}
pyramid(4)
You could do something like this:
Declare a variable res which gonna store in it, lines.
loop over number of lines and in each one switch between two symbols by using modulo %
function pyramid(n) {
let res = '';
for (let i = 1; i <= n; i++) {
let str = ' '.repeat(n - i);
let line = ['+', '&'][i % 2].repeat(i * 2 - 1);
res += str + line + "\n";
}
return res;
}
console.log(pyramid(4));
Note: \n character for a line break to add a new line into result string.
You're outputting both lines on every iteration of the loop:
let symb1 = '&'.repeat(i * 2 - 1);
let symb2 = '+'.repeat(i * 2 - 1);
console.log(str + symb1 + str);
console.log(str + symb2 + str);
Instead, conditionally output one or the other. You can check whether i is even or odd for the condition:
if (i % 2 == 1) {
let symb1 = '&'.repeat(i * 2 - 1);
console.log(str + symb1 + str);
} else {
let symb2 = '+'.repeat(i * 2 - 1);
console.log(str + symb2 + str);
}
(You can of course refactor this into something shorter, reduce repetition, etc. The point here is to demonstrate the goal of outputting one or the other instead of both.)
Use a ternary and test for even using remainder
You can push into an array and join with newlines
function pyramid(n) {
const lines = [];
for (let i = 1; i <= n; i++) {
let str = ' '.repeat(n - i);
let symb = (i%2===0 ? '+' : '&').repeat(i * 2 - 1);
lines.push(str + symb + str);
}
console.log(lines.join("\n"));
}
pyramid(4)

Round number using a js funcion not keeping the first 0

I'm making a function to round the last number when more then 3 digits after comma, but when I got like :
18093941.000
I run the function and result is:
18,94
and it shroud be
18,094.
How I fix this
here what I have done :
const round = num => Math.round(+('' + num).slice(0, 3) + '.' + ('' + num).slice(3, ('' + num).length));
function numberWithCommas(value) {
let rounded = value.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, '.');
// rounded now is 18,093,941
const test1 = rounded.split(',')[0]; // 18
const test2 = rounded.split(',')[1]; // 093
const test3 = rounded.split(',')[2]; // 941
//join test2 and test3 i got 093941
//
rounded = test1 + ',' + round(test2 + test3);
// rounded now is 18,94
// expected result is 18,094
return rounded;
}
console.log(numberWithCommas(18093941.000));
You can use Math.round and Number#toLocaleString after dividing with 1000.
function numberWithCommas(value) {
return Math.round(value / 1E3).toLocaleString("en-US");
}
console.log(numberWithCommas(18093941));
The problem is that '093' convert to int by + operator and it would be '93'. So you need to store leading zero and add to the result
Try this one:
const round = num => Math.round(+('' + num).slice(0, 3) + '.' + ('' + num).slice(3, ('' + num).length));
function numberWithCommas(value) {
let rounded = value.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, '.');
const test1 = rounded.split('.')[0];
const test2 = rounded.split('.')[1];
const test3 = rounded.split('.')[2];
var num = test2 + test3;
var zeros = "";
for (var i = 0; i < num.length; i++) {
if (num[i] == "0")
zeros += "0"
else
break;
}
rounded = test1 + ',' + zeros + round(num);
return rounded;
}
console.log(numberWithCommas(18093941.000));

Prefix notation string calculator Javascript problem

I'm making a calculator for a prefix notation string and it has covered all the normal tests that I've added to it. But I've come across one that it doesn't seem to be getting the right answer for and I'm unsure of why it seems to be having a problem with this.
I think it might have something to do with the division and subtraction when it comes to the numbers, because apart of the problem was I needed to assume that all inputs were valid, so there wouldn't be negative numbers nor would there be bad inputs IE not formatted correctly.
Here is the code and some of the test problems I inputted into it.
"+ / * 1 3 + 12 16 * 10 4" = 40.107142857142854
"+ * / - 5 3 / 1 3 + 2 2 / 3 * + 12 16 * 10 4" = 24.00267857142857 --- This is the one it doesn't like
"/ 300000 * + 12 16 * 10 40"= 26.785714285714285
function prefixEval(expression) {
let temp = expression.split(' ')
let expr = temp.reverse()
let stack = []
for (let i = 0; i < expr.length; i++) {
if (
expr[i] === '+' ||
expr[i] === '-' ||
expr[i] === '/' ||
expr[i] === '*'
) {
let j = stack.pop()
let k = stack.pop()
let temp = checkOperator(parseInt(j), parseInt(k), expr[i])
stack.push(temp)
} else {
stack.push(expr[i])
}
}
return stack
}
function checkOperator(a, b, op) {
switch (op) {
case '+':
console.log('adding' + ' ' + a + ' ' + op + ' ' + b)
console.log(a + b)
return a + b
case '-':
console.log('subtracting' + ' ' + a + ' ' + op + ' ' + b)
console.log(a - b)
return a - b
case '/':
console.log('dividing' + ' ' + a + ' ' + op + ' ' + b)
console.log(a / b)
return a / b
case '*':
console.log('multiplying' + ' ' + a + ' ' + op + ' ' + b)
console.log(a * b)
return a * b
default:
return 'this is not correct'
}
}
console.log(prefixEval('+ * / - 5 3 / 1 3 + 2 2 / 3 * + 12 16 * 10 4'))
You are using parseInt and dividing 2 by 0 which produces Infinity . To fix,
Change,
let temp = checkOperator(parseInt(j), parseInt(k), expr[i])
to
let temp = checkOperator(parseFloat(j), parseFloat(k), expr[i])
This is give you the expected answer

How to create binary to decimal in JavaScript without parseInt() [duplicate]

This question already has answers here:
How to convert binary string to decimal?
(10 answers)
Closed 3 years ago.
I was trying to create a binary to decimal converter without using parseInt ()
Heres my code :
var inp = `110010`;
var len = inp.length;
var string = inp.split("");
var counter = string.map(function(val,i){
return i;
}).reverse();
var storeBin = string.map(function(val,i){
let x ="";
if(val>0){
x += 2;
}else if(val===0){
x += 0;
}
return Math.pow(string[i]*x,counter[i]);
});
var dec=0; /* output */
for(i=0;i<len;i++){
dec += storeBin[i]
}
console.log("Entered binary "+inp);
console.log("Decimal "+dec);
When I run it:
Input: 1010
Output: Entered binary 1010
Decimal 11
But the output of binary 1010 should be 10 now 11 can someone please help me find the issue in this code
You need to do it like return val * Math.pow(2, counter[i]);.
var inp = `110010`;
var len = inp.length;
var string = inp.split("");
var counter = string.map(function(val, i) {
return i;
}).reverse();
var storeBin = string.map(function(val, i) {
return val * Math.pow(2, counter[i]);
});
var dec = 0; /* output */
for (i = 0; i < len; i++) {
dec += storeBin[i]
}
console.log("Entered binary " + inp);
console.log("Decimal " + dec);
FYI :
The correspomding deciaml number to a binary number is the sum of binary digits (dn) times their power of 2 (2^n):
decimalNum = d0 × 2^0 + d1 × 2^1 + d2 × 2^2 + ...
Even you can make it more simpler by using the Array#reduce method.
var inp = `110010`;
var dec = inp.split('').reduce(function(val, d, i, arr) {
return val + Math.pow(2, arr.length - i - 1) * d;
}, 0);
console.log("Entered binary " + inp);
console.log("Decimal " + dec);
Or with Array#reverse method.
var inp = `110010`;
var dec = inp.split('').reverse().reduce(function(val, d, i) {
return val + Math.pow(2, i) * d;
}, 0);
console.log("Entered binary " + inp);
console.log("Decimal " + dec);

Why I get "undefined" in JavaScript

Could you please help, why do I get this undefined value instead of returning a?
var a = 0;
var m = 888;
function sevens(m, a) {
if (m == 0) {
document.write("Amount of 8's is "+a+"<br>");
return a;
} else {
if(Math.floor(m % 10) == 8) {
a++;
sevens(Math.floor(m / 10), a);
} else {
sevens(Math.floor(m / 10), a);
}
}
}
document.write("in "+m + " " + "it is" + " " + sevens(m, a));
Thank you in advance.
Function needs to return something in the else statement. Like this:
function sevens(m, a){
if(m == 0){
document.write("Amount of 8's is "+a+"<br>");
return a;
}else{
if(Math.floor(m % 10) == 8){
a++;
return sevens(Math.floor(m / 10), a);
}else{
return sevens(Math.floor(m / 10), a);
}
}
}
You are not returning the function call while doing a recursion,
if(Math.floor(m % 10) == 8){
a++;
return sevens(Math.floor(m / 10), a);
}else{
return sevens(Math.floor(m / 10), a);
}
If you do not return anything inside a function, by default it will return undefined. Not in all the cases. That depends on the way you call the particular function.
Maybe you change the logic a bit, because you don't need an else part if in the then part the function is finished with return.
The other change is suspending Math.floor in combination with the remainder operator %. It returns always an integer value.
The third part is to move the call of sevens outside of the if statement, because it is anyway called.
var a = 0,
m = 888;
function sevens(m, a) {
if (m == 0) {
document.write("Amount of 8's is " + a + "<br>");
return a; // exit function, rest
} // of function is else part
if (m % 10 == 8) { // % --> int
a++;
}
return sevens(Math.floor(m / 10), a); // return result of call
}
document.write("in " + m + " " + "it is" + " " + sevens(m, a));
You forget the return, otherwise, I refactored a little bit the sevens function and you can run in code snippet.
var a = 0;
var m = 888;
function sevens(m, a) {
if (m === 0) {
document.write("Amount of 8's is " + a + "<br>");
return a;
}
if (Math.floor(m % 10) === 8) {
a += 1;
}
return sevens(Math.floor(m / 10), a);
}
document.write("in " + m + " " + "it is" + " " + sevens(m, a));

Categories

Resources