JavaScript Program to Count rotations which are divisible by 10


We are going to write a program in JavaScript that counts the number of rotations of a given number which are divisible by 10. We will loop through the rotations of the number and check if each one is divisible by 10. If a rotation is divisible, we will increment our count. In the end, we will return the count as the result of our program. This program will be useful in various applications as it provides a simple solution to check the divisibility of a number by 10.

Approach

The approach to solve this problem is as follows −

  • Initialize a counter variable to store the number of rotations.

  • Loop through the given array of numbers and generate all possible rotations.

  • For each rotation, convert the array into a single number by concatenating its elements.

  • Check if the number is divisible by 10 and if yes, increment the counter.

  • Repeat the steps 2-4 until all possible rotations have been checked.

  • Return the counter as the result.

Example

Here is an example of a JavaScript program to count rotations which are divisible by 10 −

function countRotations(arr) {
   let count = 0;
   for (let i = 0; i < arr.length; i++) {
      let rotated = arr.slice(i).concat(arr.slice(0, i));
      let rotatedString = rotated.join("");
      if (Number(rotatedString) % 10 === 0) {
         count++;
      }
   }
   return count;
}
const arr = [50, 20, 100, 10];
console.log(countRotations(arr));

Explanation

  • The countRotations function takes an array arr as input.

  • The variable count is initialized to keep track of the number of rotations that are divisible by 10.

  • The for loop iterates over the elements of arr.

  • On each iteration, the rotated array is created by concatenating a slice of the arr starting from the current index to the end, with a slice of the arr starting from the beginning to the current index.

  • The rotatedString is created by joining the elements of the rotated array using the join method.

  • The if statement checks if the number represented by the rotatedString is divisible by 10. If it is, the count is incremented.

  • Finally, the count is returned as the result.

  • In the example, the input array arr is [50, 20, 100, 10] and the output is 4 as there are 3 rotations of the array which are divisible by 10: 10010, 01001, 10001.

Updated on: 13-Mar-2023

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements