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……"
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 ......
The number of occurrences of "1" or "2" in each group is -
1 2 2 1 1 2 1 2 2 1 2 2 ......
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;
then the output should be -
const output = 3;
The first 6 characters of the magic string S The element is "12211", which contains three 1's, so 3 is returned.
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));
The output in the console will be-
3
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!