📌  相关文章
📜  Javascript程序检查两个数字是否相互旋转(1)

📅  最后修改于: 2023-12-03 15:16:18.478000             🧑  作者: Mango

Introduction to Checking if Two Numbers are Rotations of Each Other in JavaScript

Rotating a number means shifting its digits left or right and wrapping the shifted digits around. For example, rotating the number 1234 to the left by one digit results in the number 2341 and rotating it to the right by one digit results in the number 4123. In this tutorial, we'll be discussing how to check if two numbers are rotations of each other in JavaScript.

Approach

To check if two numbers are rotations of each other, we can follow the steps below:

  1. Convert the two numbers into strings and concatenate one of them with itself. This ensures that all possible rotations of one of the numbers are present in the concatenated string.

  2. Check if the other number is a substring of the concatenated string.

If the second number is a substring of the concatenated string, then the two numbers are rotations of each other. Otherwise, they are not.

Code

Below is the JavaScript function that implements the above approach:

function areRotations(num1, num2) {
  if (num1.length !== num2.length) {
    return false;
  }
  
  const concatenated = num1 + num1;
  
  return concatenated.includes(num2);
}

The function takes two parameters num1 and num2 which are the numbers to be checked. It first checks if the two numbers have the same length, as this is a necessary condition for them to be rotations of each other. If they don't have the same length, it immediately returns false.

Next, it concatenates num1 with itself to create the concatenated string. Then, it checks if num2 is a substring of the concatenated string using the includes() method. If num2 is a substring of the concatenated string, the function returns true, indicating that the two numbers are rotations of each other. Otherwise, it returns false.

Conclusion

In this tutorial, we discussed how to check if two numbers are rotations of each other in JavaScript. We followed a simple approach that involves concatenating one of the numbers with itself and checking if the other number is a substring of the resulting string. We also provided a JavaScript function that implements this approach.