Table of Contents
使用 ToString() 方法检查两个数字是否相互位循环
语法
算法
示例 2
使用 For 循环检查两个数字是否相互位循环
Home Web Front-end JS Tutorial Javascript program to check if two numbers are bit loops of each other

Javascript program to check if two numbers are bit loops of each other

Sep 01, 2023 pm 04:05 PM

Javascript 程序检查两个数字是否是彼此的位循环

问题陈述 - 我们给出了两个整数,需要检查这两个数字是否是彼此的位循环。

在 JavaScript 中,每个整数都是一个 32 位二进制数,表示 0 和 1。这里,我们需要检查是否旋转了第一个数字的 32 位字符串;我们可以在第一个数字总共 32 次旋转中获得或不获得第二个数字的 32 位字符串。

使用 ToString() 方法检查两个数字是否相互位循环

toString()方法用于将整数转换为32位二进制数字字符串。之后,我们可以在二进制字符串中添加前导零,使其长度为 32 位。接下来,我们可以将数字的二进制字符串与其自身连接起来,并检查第二个数字的二进制字符串是否作为合并字符串的子字符串存在。

语法

用户可以按照以下语法检查连接字符串后两个数字是否相互位循环。

let num1BinaryDouble = num1Binary + num1Binary;
let isBitRotation = num1BinaryDouble.includes(num2Binary)
Copy after login

算法

  • 第 1 步 - 使用 toString() 方法并传递 2 作为其参数,将两个数字转换为二进制字符串。

  • 第 2 步 - 接下来,我们需要将两个字符串的大小设置为 32 位。因此,请向两个二进制字符串添加前导零。

  • 步骤 3 - 将 num1 的二进制字符串合并到自身。

  • 步骤 4 - 检查合并后的字符串是否包含 num2 的二进制字符串。如果是,则意味着两个数字都是彼此的位循环。

示例 1

在下面的示例中,checkBitRotations() 函数实现了上述算法,以确保两个数字是否是彼此的位循环。在输出中,用户可以观察到 1 和 2 是彼此的位循环,但 1 和 5 不是。

<html>
<body>
   <h3>Checking if <i> two numbers are bit rotations of each other or not </i> in JavaScript</h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let num1 = 1;
      let num2 = 2;
      let num3 = 5;
      function checkBitRotation(num1, num2) {
         let num1Binary = num1.toString(2);
         let num2Binary = num2.toString(2);
         // append remaining zeros at the start of num1BInary and num2Binary to make it's length 32
         while (num1Binary.length < 32) {
            num1Binary = "0" + num1Binary;
         }
         while (num2Binary.length < 32) {
            num2Binary = "0" + num2Binary;
         }
         // double the string
         let num1BinaryDouble = num1Binary + num1Binary;
         // check if num2Binary is present in num1BinaryDouble
         if (num1BinaryDouble.includes(num2Binary)) {
            return true;
         } else {
            return false;
         }
      }
      output.innerHTML += "The " + num1 + " and " + num2 + " are bit rotations of each other " + checkBitRotation(num1, num2) + "<br>";
      output.innerHTML += "The " + num1 + " and " + num3 + " are bit rotations of each other " + checkBitRotation(num1, num3) + "<br>";
   </script>
</body>
</html>
Copy after login

使用 For 循环检查两个数字是否相互位循环

在这种方法中,我们将把数字转换为二进制字符串。之后,我们将使用 for 循环获取第一个数字的所有旋转,并将所有旋转与第二个数字进行比较。如果第一个数字的任何旋转与第二个数字匹配,则它们是彼此的位旋转。

语法

用户可以按照下面的语法来匹配第一个数字与第二个数字的所有旋转,并确保它们是彼此的位旋转。

for (let i = 0; i < num1Binary.length; i++) {
   if (num1Binary === num2Binary) {
      return true;
   }
   num1Binary = num1Binary[num1Binary.length - 1] + num1Binary.substring(0, num1Binary.length - 1);
}
Copy after login

在上面的语法中,我们将第一个数字与第二个数字逐一进行比较,如果匹配,则返回 true。

算法

  • 第 1 步 - 使用 toString() 方法将两个数字转换为二进制字符串。

  • 第 2 步 - 现在,附加前导零以使它们的长度相等。

  • 第 3 步 - 使用 for 循环迭代第一个字符串。

  • 第 4 步 - 如果 num1Binary 与 num2Binary 匹配,则返回 true。

  • 步骤 5 - 在 for 循环中,如果第一个数字的当前旋转与第二个数字不匹配,则旋转第一个数字并获得新的旋转。

  • 第 6 步 - 继续将下一个轮换与第二个轮换匹配,直到任何轮换匹配。如果任何旋转不匹配,则返回 false。

示例 2

在下面的示例中,我们实现了上述算法来检查位旋转。在这里,我们逐一获取第一个数字的每次旋转,并将它们与第二个数字进行比较。如果任何旋转匹配,我们将返回 true,用户可以在输出中观察到。

<html>
<body>
   <h3>Checking if <i> two numbers are bit rotations of each other or not </i> in JavaScript</h3>
   <div id = "output"> </div>
   <script>
      let output = document.getElementById("output");
      let num1 = 122;
      let num2 = 2147483678;
      let num3 = 1;
      function checkBitRotation(num1, num2) {
         let num1Binary = num1.toString(2);
         let num2Binary = num2.toString(2);
         // adding leading zeros to make both numbers of the same length
         while (num1Binary.length < num2Binary.length) {
            num1Binary = "0" + num1Binary;
         }
         // checking num1Binary and num2Binary are rotations of each other using for loop
         for (let i = 0; i < num1Binary.length; i++) {
            if (num1Binary === num2Binary) {
               return true;
            }
            num1Binary = num1Binary[num1Binary.length - 1] + num1Binary.substring(0, num1Binary.length - 1);
         }
         return false;
      }
      output.innerHTML += "The " + num1 + " and " + num2 + " are bit rotations of each other " + checkBitRotation(num1, num2) + "<br>";
      output.innerHTML += "The " + num1 + " and " + num3 + " are bit rotations of each other " + checkBitRotation(num1, num3) + "<br>";
   </script>
</body>
</html>
Copy after login

用户学习了两种不同的方法来检查两个数字是否是彼此的位循环。在第一种方法中,我们将第一个字符串与其自身连接起来,并检查第二个数字是否作为子字符串存在。在第二种方法中,我们使用 for 循环找到第一个数字的所有位旋转,并将它们与第二个数字进行匹配。

The above is the detailed content of Javascript program to check if two numbers are bit loops of each other. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles