10 Days of JavaScript Hackerrank Solution

The "10 Days of JavaScript" program consists of a series of tutorials and challenges available on the HackerRank platform. HackerRank has established a reputation for providing difficult programming problems that are essential for programmers to excel in coding interviews, serving as fundamental building blocks in a learner's educational path.

The "10 Days of JavaScript" program is designed to comprehensively address all facets of JavaScript, ranging from introductory topics to more complex subjects. Engaging with these challenges guarantees that participants develop a solid understanding of the essential principles of JavaScript.

Addressing these challenges can occasionally be difficult, and considering recommendations as well as examining solutions can prove beneficial in these situations. This article is designed to assist you in this regard. Within its contents, we will explore the resolutions to the issues presented for each day of the 10 days of JavaScript from HackerRank.

Day 0: Hello World!

The "Hello World" segment of the 10 Days of JavaScript program addresses the fundamental aspects of the language, guiding learners through the initial concepts associated with programming. This section encompasses output printing, the use of identifiers, the inclusion of comments, foundational syntax, and the various types of literals within the JavaScript programming language.

Problem:

The editor supplies a greeting function that includes a parameter named parameterVariable. To complete this task, utilize console.log to output "Hello, World!" along with the value contained in parameterVariable.

Solution:

Example

function greeting(parameterVariable) {
  // This line prints 'Hello, World!' to the console:
  console.log('Hello, World!');

  // Print the contents of the parameterVariable on a new line:
  console.log(parameterVariable);
}

The editor includes a greeting function that outputs the message "Hello, World!" by default.

The missing line has been included: console.log(parameterVariable). This line outputs the value of the parameterVariable argument provided to the function.

Day 0: Data Types

The upcoming chapter explores a crucial concept in JavaScript: data types. The segment on Data Types in the 10 Days of JavaScript encompasses a comprehensive overview of all data types, types of operators, the nature of dynamic typing, the conventions for naming variables, as well as the processes of declaration and initialization, among other related topics.

Problem:

The editor initializes the variables firstInteger, firstDecimal, and firstString. You are required to utilize the + operator to join firstString with secondString, convert secondDecimal into a floating-point number and then add it to firstDecimal, and transform secondInteger into an integer before adding it to firstInteger. Ensure that firstString is displayed first when you output the result on a new line.

Solution:

Example

function performOperation(secondInteger, secondDecimal, secondString) {
  // Declare a variable named 'firstInteger' and initialize with integer value 4.
  const firstInteger = 4;

  // Declare a variable named 'firstDecimal' and initialize with floating-point value 4.0.
  const firstDecimal = 4.0;

  // Declare a variable named 'firstString' and initialize it with the string "HackerRank ".
  const firstString = 'HackerRank ';

  // 1. The sum of firstInteger and secondInteger (converted to integer)
  console.log(firstInteger + Number(secondInteger));

  // 2. The sum of firstDecimal and secondDecimal (converted to float)
  console.log(firstDecimal + parseFloat(secondDecimal));

  // 3. Concatenation of firstString and secondString
  console.log(firstString + secondString);
}

The functionality for operations including the concatenation of the first and second strings, the addition of the first and second integers, and the addition of the first and second decimal values is encapsulated within the perform Operation function. This function converts the secondInteger string into a floating-point number, subsequently changes it to a numerical format, and returns the result. Within this function, the concatenation operator, +, is employed.

Day 1: Arithmetic Operators

The Arithmetic Operators segment of the 10 Days of JavaScript addresses a fundamental aspect of JavaScript: the concept of operators. This part categorizes operators into unary, binary, and ternary types, while also delving into the specifics of arithmetic operators.

Problem:

In the editor provided below, complete the subsequent tasks:

  • The function getArea(length, width) calculates and returns the area of a rectangle defined by its length and width.
  • The function getPerimeter(length, width) calculates and provides the perimeter of a rectangle characterized by its length and width.

Solution:

Example

function getArea(length, width) {
  // Area of a rectangle is length multiplied by width
  const area = length * width;
  return area;
}

function getPerimeter(length, width) {
  // Perimeter of a rectangle is 2(length + width)
  const perimeter = 2 * (length + width);
  return perimeter;
}

The functions getArea and getPerimeter are designed to compute the area and perimeter, respectively, by employing the formulas length width for the area and 2 (length + width) for the perimeter, returning the resultant values.

Day 1: Functions

This chapter delves into the fundamentals of advanced functions in JavaScript and presents a crucial programming concept: recursion. Recursion is defined as a scenario where a function invokes itself within its own definition.

Problem:

Create a function that accepts a parameter n and computes its factorial, which is denoted as n!.

Solution:

Example

function factorial(n) {
  if (n === 0 || n === 1) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}
console.log(factorial(5)); // Output: 120

The factorial function accepts a parameter n and yields 1 when n is either 0 or 1. In all other cases, the function computes the result by multiplying n by factorial(n-1). This illustrates the use of recursion to determine the factorial of a specified number. An alternative method to tackle this issue involves utilizing loops.

Day 2: let and const

This section of the series examines the use of let, var, and const in JavaScript. Each of these declarations serves distinct purposes in various contexts, and this chapter delves into their significance and application. Completing the following challenge will help solidify your understanding of this topic.

Problem:

Define a constant variable named PI and assign it the value of Math.PI. Following that, retrieve a value from standard input that denotes the radius of a circle, labeled as r. Utilize both PI and r to calculate the area and the circumference of a circle with radius r. Finally, output both the circumference and the area using console.log.

Solution:

Example

function main() {
    // Declare a constant variable PI and give it the value Math.PI
    const PI = Math.PI;

    // Read a value from stdin that represents a circle's radius, r
    const radius = parseFloat(readLine());

    // Calculate the area of the circle
    const area = PI * Math.pow(radius, 2);

    // Calculate the perimeter (or parameter) of the circle
    const perimeter = 2 * PI * radius;

    // Print the area and perimeter of the circle
    console.log(area);
    console.log(perimeter);
}

This snippet of code initializes a constant variable named PI, assigning it the value of Math.PI. Subsequently, the radius of the circle is obtained from standard input (stdin). Utilizing the provided formulas, the area and circumference of the circle are calculated, and the outcomes are displayed through console.log.

Day 3: Conditional Statements: If-Else

The initial chapter regarding conditional statements introduces if-else constructs, which are applicable in a variety of situations. The following problem offers a practical challenge to enhance your understanding.

Problem:

Complete the implementation of the editor's getGrade(score) function. This function takes a single integer argument that indicates the total score Julia achieved on her exam. The function should return the corresponding letter grade based on that score.

Solution:

Example

function getGrade(score) {
  let grade;
  if (score >= 90) {
    grade = 'A';
  } else if (score >= 80) {
    grade = 'B';
  } else if (score >= 70) {
    grade = 'C';
  } else if (score >= 60) {
    grade = 'D';
  } else {
    grade = 'F';
  }
  return grade;
}

The provided code specifies a function named getGrade, which accepts an integer score as an argument and returns the corresponding letter grade. It employs a sequence of if-else statements to ascertain the correct grade according to these guidelines: if the score is at least 90, it assigns "A"; if the score is at least 80 but less than 90, it gives "B"; for scores from 70 to 79, it returns "C"; if the score falls between 60 and 69, it results in a "D". Any score below 60 will receive an "F".

Day 3: Conditional Statements: Switch

In this section, we will explore another significant conditional construct known as the switch statement. This feature enables you to evaluate multiple scenarios without resorting to the cumbersome if-else-if chain.

Problem:

Finalize the getLetter(s) function within the editor. This function accepts a single argument: a string comprised solely of lowercase English letters (specifically, a through z). The function is required to output either A, B, C, or D based on the criteria outlined below:

Solution:

Example

function getLetter(s) {
    let letter;
    switch (s[0]) {
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
            letter = 'A';
            break;
        case 'b':
        case 'c':
        case 'd':
        case 'f':
        case 'g':
            letter = 'B';
            break;
        case 'h':
        case 'j':
        case 'k':
        case 'l':
        case 'm':
            letter = 'C';
            break;
        Default:
            letter = 'D';
            break;
    }
    return letter;
}

The following code defines the method getLetter, which identifies the category of the initial letter in a given string s. It employs a switch statement along with the input string s. The function adheres to the specifications outlined in the challenge to ascertain the corresponding letter ('A, B, C, or D').

Day 3: Loops

This section delves into several JavaScript looping methodologies and provides an in-depth examination of essential control flow mechanisms. It includes discussions on for, while, do-while, for-in, and for-of loops.

Problem:

To begin with, display each vowel on a separate line. The vowels in the English language consist of a, e, i, o, and u, and it is essential to print each vowel in the exact sequence that it occurs.

Secondly, output each consonant (that is, any letter that is not a vowel) on a separate line, maintaining the original sequence in which they appeared.

Solution:

Example

function vowelsAndConsonants(s) {
    const vowels = 'aeiou';
    let consonants = '';

    for (let char of s) {
        if (vowels.includes(char)) {
            console.log(char);
        } else {
            consonants += char + '\n';
        }
    }

    console.log(consonants.trim());
}

// Example:
// If the input string is "javascriptloops"
// Output:
// a
// a
// i
// o
// o
// e
// j
// v
// s
// c
// r
// p
// t
// l
// p
// s

The provided code establishes the function vowelsAndConsonants, which processes each character in the given input string. It checks whether each character is a vowel; if it is, the function outputs it on a fresh line. Conversely, if the character is a consonant, it is appended to the consonant string, and subsequently, the entire collection of consonants is printed on individual lines following the vowels.

Day 4: Arrays

This section delivers a comprehensive examination of fundamental operations involving arrays in JavaScript, empowering you to fully leverage the functionalities offered by this versatile data structure. It begins with the creation of arrays and progresses through key topics such as indexing and retrieving elements from array objects.

Problem:

This exercise focuses on arrays and their application in Python programming. The function getSecondLargest accepts an array of integers as its parameter and outputs the second largest value found within that array.

Solution:

Example

function getSecondLargest(nums) {
    // Remove duplicates by converting the array to a Set and then back to an array
    const uniqueNums = Array.from(new Set(nums));

    // Sort the array in descending order
    const sortedNums = uniqueNums.sort((a, b) => b - a);

    // Return the second element in the sorted array
    return sortedNums[1];
}

function main() {
    const n = +(readLine());
    const nums = readLine().split(' ').map(Number);
    
    console.log(getSecondLargest(nums));
}

This approach eliminates duplicate entries from the array, arranges the remaining values in descending order, and subsequently returns the second element, representing the second largest value.

Day 4: Try, Catch, and Finally

In this chapter, we will elucidate two fundamental aspects of JavaScript programming: "String Basics" and "Error Handling."

Problem:

The reverseString function employs split, reverse, and join methods to reverse a given string, referred to as s. In the event that an exception occurs, a new line will output an error message. If the process completes successfully without any exceptions, the function will return the reversed string; otherwise, it will return the original string.

Solution:

Example

function reverseString(s) {
    try {
        // Attempt to reverse the string using split, reverse, and join
        const reversedString = s.split('').reverse().join('');
        console.log(reversedString);
    } catch (error) {
        // Catch and print the exception's message if an error occurs
        console.log(error.message);
    } finally {
        // Print the original string regardless of success or failure
        console.log(s);
    }
}

// Example usage:
const inputString = "Hello, World!";
reverseString(inputString);

This function endeavors to invert the provided string by utilizing the split, reverse, and join methods.

Day 4: Throw

This section addresses JavaScript errors by exploring the concepts of try, catch, finally, and throw. Consequently, it provides a comprehensive overview of error handling in JavaScript.

Problem:

The parameter for the isPositive function is an integer designated as a. This function yields YES when a is found to be positive and raises an error in all other scenarios. Specifically, it generates a Negative Error if a is negative and produces a Zero Error if the value equals 0.

Solution:

Example

function isPositive(a) {
    if (a > 0) {
        return "YES";
    } else if (a === 0) {
        throw new Error("Zero Error");
    } else {
        throw new Error("Negative Error");
    }
}

// Example usage:
try {
    const result = isPositive(5); // Change the argument to test different cases
    console.log(result);
} catch (error) {
    console.log(error.message);
}

This function assesses if the provided integer is positive. It returns the string "YES" when the integer is greater than zero. If the integer is exactly zero, it raises an error accompanied by the message "Zero Error." Additionally, if the integer is less than zero, it generates an error with the message "Negative Error."

Day 5: Create a Rectangle Object

This chapter delves into the concept of JavaScript objects. It begins with a fundamental overview and subsequently moves on to the process of constructing objects.

Problem:

The Rectangle function creates an object that symbolizes a rectangle and takes two parameters, a and b. This rectangle object must include the following attributes: the area, which is calculated as the product of its length and width; the perimeter, which is determined by the sum of its length and width; and the length, which is defined as a.

Solution:

Example

function Rectangle(a, b) {
  this.length = a;
  this.width = b;
  this.perimeter = 2 * (a + b);
  this.area = a * b;
}

const rect = new Rectangle(5, 3);
console.log(rect.length); // Output: 5
console.log(rect.width); // Output: 3
console.log(rect.perimeter); // Output: 16
console.log(rect.area); // Output: 15

The code presented above effectively addresses the specified problem.

Day 5: Count Objects

This section discusses the use of for, for...in, and forEach loops for the purpose of counting objects.

Problem:

The editor function necessitates the provision of an array comprising objects, each containing two integer attributes: x and y. The purpose of this function is to calculate and return the total number of objects, denoted as o, within the array for which the condition o.x == o.y holds true.

Solution:

Example

function getCount(objects) {
    let count = 0;

    for (let obj of objects) {
        if (obj.x === obj.y) {
            count++;
        }
    }

    return count;
}

// Example usage:
const sampleObjects = [
    { x: 1, y: 1 },
    { x: 2, y: 3 },
    { x: 4, y: 4 },
    { x: 5, y: 5 },
];

const result = getCount(sampleObjects);
console.log(result); // Output: 3

Day 5: Classes

This section delves into the fundamental principles of object-oriented programming within the context of JavaScript.

Problem:

Create a Polygon class and evaluate the perimeter method along with the constructor in the code editor. The constructor takes an array of integer values representing the lengths of the sides, and the perimeter method calculates and returns the total perimeter of the polygon.

Solution:

Example

class Polygon {
    constructor(sideLengths) {
        this.sideLengths = sideLengths;
    }

    perimeter() {
        return this.sideLengths.reduce((sum, side) => sum + side, 0);
    }
}

// Example usage:
const polygon = new Polygon([3, 4, 5, 6]);
console.log(polygon.perimeter()); // Output: 18

This code provides the full implementation of the solution for the specified problem.

Day 6: Inheritance

This segment of the 10 Days of JavaScript series addresses the fundamental concepts of inheritance within JavaScript.

Problem:

The editor provides an implementation of a Rectangle class; to make use of it, you need to incorporate an area method into the prototype and create a Square class that extends Rectangle. This Square class should include a constructor and should be capable of utilizing the area method from the Rectangle class.

Solution:

Example

class Rectangle {
    constructor(w, h) {
        this.w = w;
        this.h = h;
    }

    area() {
        return this.w * this.h;
    }
}

// Create a Square class that inherits from Rectangle
class Square extends Rectangle {
    constructor(side) {
        // Call the constructor of the parent class (Rectangle)
        super(side, side);
    }
}

// Example usage
if (JSON.stringify(Object.getOwnPropertyNames(Square.prototype)) === JSON.stringify(['constructor'])) {
    const rec = new Rectangle(3, 4);
    const sqr = new Square(3);

    console.log(rec.area()); // Output: 12
    console.log(sqr.area()); // Output: 9
} else {
    console.log(-1);
    console.log(-1);
}

The Square class is established as a subclass of Rectangle by utilizing the extends keyword, while the Rectangle class possesses an area method designed for calculating the area of the rectangle. The Square class implements its constructor with a side length through Super(side, side).

Day 6: Template Literals

Problem:

The function named sides, designed to take in literals, an array of strings, and expressions, along with a rest parameter that captures values provided through string interpolation, is essential for addressing the issue at hand. By utilizing the equations s₁ and s₂ = (P ± √(P² - 16A)) / 4, this function should effectively calculate the lengths of the sides of a rectangle based on its area and perimeter.

Solution:

Example

function sides(literals, ...expressions) {
  // Extract the area and perimeter from the expressions array
  const [area, perimeter] = expressions;

  // Calculate s1 and s2 using the formula
  const s1 = (perimeter + Math.sqrt(perimeter * perimeter - (16 * area))) / 4;
  const s2 = (perimeter - Math.sqrt(perimeter * perimeter - (16 * area))) / 4;

  // Sort s1 and s2 in ascending order
  const sortedSides = [s1, s2].sort((a, b) => a - b);

  // Return the sorted array of side lengths
  return sortedSides;
}

const result = sides`The area is: ${area}, the perimeter is: ${perimeter}. 
The sides are: ${sides[0]} and ${sides[1]}.`;
console.log(result);

Day 6: Arrow Functions

This section delves into the concept and application of arrow functions.

Problem:

The editor's role involves taking an array, referred to as nums, and adjusting its elements by multiplying even numbers by two and odd numbers by three. This process is carried out through a complete traversal of the array, after which the modified array is returned.

Solution:

Example

function modifyArray(nums) {
    // Iterate through the array and modify elements based on their parity
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] % 2 === 0) {
            // If the element is even, multiply by 2
            nums[i] *= 2;
        } else {
            // If the element is odd, multiply by 3
            nums[i] *= 3;
        }
    }

    // Return the modified array
    return nums;
}

// Example usage
const originalArray = [1, 2, 3, 4, 5];
const modifiedArray = modifyArray(originalArray);

console.log("Original Array:", originalArray);   // Output: [1, 2, 3, 4, 5]
console.log("Modified Array:", modifiedArray);   // Output: [3, 4, 9, 8, 15]

Day 7: Bitwise Operator

This chapter delves into bitwise operators in JavaScript. It begins by discussing conversions between number systems and subsequently examines each bitwise operator with practical examples of their application.

Problem:

The objective is to identify the maximum bitwise AND result that is below a given integer, k, for any pair of numbers, a and b, taken from a sequence S.

Solution:

Example

function getMaxLessThanK(n, k) {
  // Initialize the result variable to 0
  let result = 0;

  // Iterate from n - 1 down to 1 (excluding n)
  for (let i = n - 1; i > 0; i--) {
    // Perform bitwise AND between the current element (i) and the result
    result = result & i;

    // Check if the result is no longer less than k
    if (result >= k) {
      break;
    }
  }

  // Return the final result
  return result;
}

Day 7: JavaScript Dates

This section delves into handling dates and times within JavaScript, as well as the approach to retrieve dates using the get methods.

Problem:

The function outputs the name of the day corresponding to a date string formatted as MM/DD/YYYY. The possible outcomes include Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, or Saturday. For instance, an example date could be 12/07/2016.

Solution:

Example

function getDayName(dateString) {
    const daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

    // Create a Date object from the dateString
    const dateObject = new Date(dateString);

    // Get the day of the week index (0 for Sunday, 1 for Monday, and so on)
    const dayIndex = dateObject.getUTCDay();

    // Get the day name based on the index
    dayName = daysOfWeek[dayIndex];

    return dayName;
}

// Example usage
const exampleDateString = "12/07/2016";
const dayName = getDayName(exampleDateString);

console.log(`The day name for ${exampleDateString} is: ${dayName}`);

Day 8: Regular Expressions I

This chapter explores the fundamental concepts of regular expressions within the JavaScript programming language.

Problem:

To create a RegExp object, denoted as re, which matches any string s that begins and concludes with the identical vowel, you will need to finalize the method provided in the editor below. It is important to note that in the English language, there are five vowels: a, e, i, o, and u.

Solution:

Example

function regexVar() {
    /*
     * Declare a RegExp object variable named 're'
     * It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u})
     */

    // Using a regular expression with a capturing group for a vowel and a backreference,
    let re = /^([aeiou]).*\1$/;

    /*
     * Do not remove the return statement
     */
    return re;
}

// Example usage
const regex = regexVar();
const testString = "abcda"; // Replace this with any test string
console.log(regex.test(testString)); // Output: true or false

Day 8: Regular Expressions II

Addresses intermediate concepts related to regular expressions within the JavaScript programming language.

Problem:

The approach utilized by the editor generates a RegExp object referred to as re, designed to identify any text that fulfills two criteria: the string should start with one of the prefixes Mr., Mrs., Ms., Dr., or Er, and the subsequent characters must consist of uppercase, lowercase, or capital letters from the English alphabet.

Solution:

Example

function regexVar() {
    /*
     * Declare a RegExp object variable named 're'
     * It must match a string that starts with 'Mr.', 'Mrs.', 'Ms.', 'Dr.', or 'Er.', 
     * followed by one or more letters.
     */

    let re = /^(Mr\.|Mrs\.|Ms\.|Dr\.|Er\.)[a-zA-Z]+$/;

    /*
     * Do not remove the return statement
     */
    return re;
}

// Example usage
const regex = regexVar();
const testString = "Mr. Smith"; // Replace this with any test string
console.log(regex.test(testString)); // Output: true or false

Day 8: Regular Expressions III

This section of day 7 delves into the more complex aspects of regular expressions as utilized in JavaScript.

Problem:

In the provided editor, complete the function by returning a RegExp object, named re, that matches every number found within a given string s.

Solution:

Example

function regexVar() {
    /*
     * Declare a RegExp object variable named 're'
     * It must match ALL occurrences of numbers in a string.
     */

    let re = /\d+/g;

    /*
     * Do not remove the return statement
     */
    return re;
}

// Example usage
const regex = regexVar();
const testString = "There are 123 apples and 456 oranges in the basket.";
console.log(testString.match(regex)); // Output: ['123', '456']

Day 9: Create a Button

In this section, we will delve into the process of creating buttons using HTML and incorporating interactive features through JavaScript.

Problem:

To create a clickable button that meets the specified requirements, follow these steps:

  1. Create the button element in your HTML with the relevant properties.
  2. Apply the necessary styles to set its dimensions and font size.
  3. Implement a JavaScript function to update the button's text label upon each click.

Here’s an example of how to accomplish this:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Clickable Button Example</title>
    <style>
        #btn {
            width: 96px;
            height: 48px;
            font-size: 24px;
        }
    </style>
</head>
<body>
    <button id="btn">0</button>

    <script>
        const button = document.getElementById('btn');
        button.addEventListener('click', function() {
            let currentValue = parseInt(button.innerHTML, 10);
            button.innerHTML = currentValue + 1;
        });
    </script>
</body>
</html>

In this example:

  • The button is created with an ID of btn.
  • The CSS styles are applied to establish a width of 96 pixels, a height of 48 pixels, and a font size of 24 pixels.
  • The button’s initial text label is set to 0.
  • A click event listener is added to the button that increments the displayed number by 1 each time it is clicked. The button's text is updated using the innerHTML property.

Solution:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #btn {
            width: 96px;
            height: 48px;
            font-size: 24px;
        }
    </style>
    <title>Clickable Button</title>
</head>
<body>

<button id="btn" onclick="incrementButtonClick()">0</button>

<script>
    let clickCount = 0;

    function incrementButtonClick() {
        clickCount++;
        document.getElementById("btn").innerHTML = clickCount;
    }
</script>

</body>
</html>

Day 9: Buttons Container

This section delves into the process of constructing button containers and adjusting button layouts through the use of JavaScript.

Problem:

The objective is to develop a total of nine buttons within a div element, arranged in a 3x3 grid format, each labeled uniquely from 1 to 9. Additionally, it is essential that when the center button is activated, the buttons located on the outer edges rotate in a clockwise direction. The implementation should adhere to specific guidelines set forth in the code editor.

Solution:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        #btns {
            width: 30%;
            margin: auto;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 5px;
        }

        button {
            width: 100%;
            height: 48px;
            font-size: 24px;
        }
    </style>
    <title>Rotating Buttons</title>
</head>
<body>

<div id="btns">
    <button id="btn1" onclick="rotateButtons()">1</button>
    <button id="btn2" onclick="rotateButtons()">2</button>
    <button id="btn3" onclick="rotateButtons()">3</button>
    <button id="btn4" onclick="rotateButtons()">4</button>
    <button id="btn5" onclick="rotateButtons()">5</button>
    <button id="btn6" onclick="rotateButtons()">6</button>
    <button id="btn7" onclick="rotateButtons()">7</button>
    <button id="btn8" onclick="rotateButtons()">8</button>
    <button id="btn9" onclick="rotateButtons()">9</button>
</div>

<script>
    function rotateButtons() {
        const outerButtonIds = ["btn1", "btn2", "btn3", "btn6", "btn9", "btn8", "btn7", "btn4"];
        const outerButtonValues = outerButtonIds.map(id => document.getElementById(id).innerHTML);

        // Rotate the values in a clockwise direction
        const rotatedValues = [outerButtonValues[7], ...outerButtonValues.slice(0, 7)];

        // Update the innerHTML of the outer buttons
        for (let i = 0; i < outerButtonIds.length; i++) {
            document.getElementById(outerButtonIds[i]).innerHTML = rotatedValues[i];
        }
    }
</script>

</body>
</html>

Day 10: Binary Calculator

This chapter discusses the development of a calculator that utilizes various events.

Problem:

Create a straightforward calculator capable of executing the following operations on binary numbers: addition, subtraction, multiplication, and division. It is important to note that the division operation must strictly adhere to integer division; for instance, 1001 divided by 100 results in 10.

Solution:

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            width: 33%;
        }

        #res {
            background-color: lightgray;
            border: 1px solid black;
            height: 48px;
            font-size: 20px;
            padding: 5px;
            text-align: right;
            overflow: hidden;
        }

        button {
            width: 25%;
            height: 36px;
            font-size: 18px;
            margin: 0;
            float: left;
        }

        #btn0, #btn1 {
            background-color: lightgreen;
            color: brown;
        }

        #btnClr, #btnEql {
            background-color: darkgreen;
            color: white;
        }

        #btnSum, #btnSub, #btnMul, #btnDiv {
            background-color: black;
            color: red;
        }

        #btns {
            margin-top: 10px;
            overflow: hidden;
        }
    </style>
    <title>Binary Calculator</title>
</head>
<body>

<div id="res"></div>
<div id="btns">
    <button id="btn0" onclick="appendToResult('0')">0</button>
    <button id="btn1" onclick="appendToResult('1')">1</button>
    <button id="btnClr" onclick="clearResult()">C</button>
    <button id="btnEql" onclick="evaluateResult()">=</button>
    <button id="btnSum" onclick="appendToResult('+')">+</button>
    <button id="btnSub" onclick="appendToResult('-')">-</button>
    <button id="btnMul" onclick="appendToResult('*')">*</button>
    <button id="btnDiv" onclick="appendToResult('/')">/</button>
</div>

<script>
    function appendToResult(value) {
        document.getElementById('res').innerHTML += value;
    }

    function clearResult() {
        document.getElementById('res').innerHTML = '';
    }

    function evaluateResult() {
        try {
            const result = eval(document.getElementById('res').innerHTML);
            document.getElementById('res').innerHTML = result.toString(2);
        } catch (error) {
            document.getElementById('res').innerHTML = 'Error';
        }
    }
</script>

</body>
</html>

Input Required

This code uses input(). Please provide values below: