Day 9: Binary Calculator | 10 Days of JavaScript – Hacker Rank Solution

Day 9: Binary Calculator | 10 Days of JavaScript – Hacker Rank Solution: Hey Guy’s In this post we are solving Day 9: Binary Calculator which is a part of 10 Days of JavaScript Series.

Day 9: Binary Calculator | 10 Days of JavaScript – Hacker Rank Solution

Objective

In this challenge, we implement a calculator that uses binary numbers. Check out the attached tutorial for learning materials.

Task

Implement a simple calculator that performs the following operations on binary numbers: addition, subtraction, multiplication, and division. Note that division operation must be integer division only; for example, 1001/100 = 101110/101 = 10, and 101/1 = 101.

  • The calculator’s initial state must look like this:
  • Element IDs. Each element in the document must have an id, specified below:
  • tyling. The document’s elements must have the following styles:
    • body has a width of 33%.
    • res has a background-color of lightgray, a border that is solid, a height of 48px, and a font-size of 20px.
    • btn0 and btn1 have a background-color of lightgreen and a color of brown.
    • btnClr and btnEql have a background-color of darkgreen and a color of white.
    • btnSumbtnSubbtnMul, and btnDiv have a background-color of black, a color of red.
    • All the buttons in btns have a width of 25%, a height of 36px, a font-size of 18pxmargin of 0px, and float value left.

Constraints

  • All expressions in the test dataset are entered in the form operand1 => operator1 => operand2 =>, where operand1 is the first binary number, operand2 is the second binary number, {+, -, -, =} and  is in the set .
  • Both operands will always be positive integers when converted from base-2 to base-10.
  • All expressions will be valid.


Day 9: Binary Calculator | 10 Days of JavaScript – Hacker Rank Solution

   btnClr.onclick = function() {
    res.innerHTML = "";
}
btnEql.onclick = function() {
    let s = res.innerHTML;
    s = Math.floor(eval(s.replace(/([01]+)/g, '0b$1'))).toString(2);
    res.innerHTML = s;
}
btn0.onclick = function() {
    res.innerHTML += "0";
}
btn1.onclick = function() {
    res.innerHTML += "1";
}
btnSum.onclick = function() {
    res.innerHTML += "+";
}
btnSub.onclick = function() {
    res.innerHTML += "-";
}
btnMul.onclick = function() {
    res.innerHTML += "*";
}
btnDiv.onclick = function() {
    res.innerHTML += "/";
}

Disclaimer: The above Problem (Day 9: Binary Calculator) is generated by Hackerrank but the Solution is Provided by Chase2Learn. This tutorial is only for Educational and Learning purposes. Authority if any of the queries regarding this post or website fill the following contact form thank you.

Leave a Comment