Home > Web Front-end > JS Tutorial > body text

Magic Strings: Problems in JavaScript

王林
Release: 2023-09-08 12:17:05
forward
925 people have browsed it

神奇的字符串:JavaScript 中的问题

Question

The magic string str consists of only '1' and '2' and follows the following rules -

characters The string str is magical because it concatenates consecutive occurrences of the numeric characters "1" and "2" to generate the string str itself.

The first few elements of string str are as follows-

str = "1221121221221121122……"
Copy after login

If we group the consecutive '1' and '2' in str, it will be-

1 22 11 2 1 22 1 22 11 2 11 22 ......
Copy after login

The number of occurrences of "1" or "2" in each group is -

1 2 2 1 1 2 1 2 2 1 2 2 ......
Copy after login

We can see that the above sequence of occurrences is the string itself.

We give an integer num as input, and we need to return the number of '1's in the first num in the string. The magic string str.

For example, if the input of the function is -

const num = 6;
Copy after login

then the output should be -

const output = 3;
Copy after login

Output description:

The first 6 characters of the magic string S The element is "12211", which contains three 1's, so 3 is returned.

Example

The code is -

Live demo

const num = 6;
const magicalString = (num = 1) => {
   let ind = 12;
   let str = '1221121221221121122';
   while(str.length < num){
      const end = str.substring(str.length - 1) === '2' ? '1' : '2';
      str = parseInt(str.substring(ind, ind + 1)) === 2 ? str + end + end : str + end;
      ind++;
   };
   return (str.substring(0, num).match(/1/g)||[]).length;
};
console.log(magicalString(num));
Copy after login

Output

The output in the console will be-

3
Copy after login

The above is the detailed content of Magic Strings: Problems in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!