Home >Web Front-end >JS Tutorial >JavaScript FAQ Black and White Cards

JavaScript FAQ Black and White Cards

巴扎黑
巴扎黑Original
2017-07-20 14:15:431314browse
Problem description:

Time limit: 1 second

Space limit: 32768K

Niu Niu has n cards arranged in a sequence. One side of each card is black and the other side is white. In the initial state, some cards are black facing up, and some cards are white facing up. Niu Niu now wants to turn over some cards to obtain an alternating arrangement, that is, the colors of each pair of adjacent cards are different. Niu Niu wants to know the minimum number of cards that need to be flipped to form an alternating arrangement.
Input description:
输入包括一个字符串S,字符串长度length(3 ≤ length ≤ 50),其中只包含'W'和'B'两种字符串,分别表示白色和黑色。整个字符串表示卡片序列的初始状态。
Output description:
输出一个整数,表示牛牛最多需要翻转的次数。
Input example 1:
BBBW
Output example 1:
1

Solution idea:

// Change the white in the even-numbered positions to black and the black in the odd-numbered positions to white
// Turn the white at odd-numbered positions into black, and turn the black at even-numbered positions into white.

Source code:

 1 (function main(){ 2     var line = readline().split(' '); 3     var count_1; 4     var count_2; 5     var arr=line[0]; 6     count_1=Turnover(arr,'B','W'); 7     count_2=Turnover(arr,'W','B'); 8     if (count_1<count_2) { 9         print(count_1);10     }else{11         print(count_2);12     }13 })();14 function  Turnover(str,card1,card2){15     var count=0;16     for(var i=0;i<str.length;i++){17         if(i%2==0&&str[i]!=card1){18             str[i]=card1;19             count++;20         }else if(i%2==1&&str[i]!=card2){21             str[i]=card2;22             count++;23         }24     }25     return count;26 }
Card

The above is the detailed content of JavaScript FAQ Black and White Cards. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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