Calculate score for the given binary string | C ++ implementation of the approach ; Function to return the score for the given binary string ; Traverse through string character ; Initialize current chunk 's size ; Get current character ; Calculate total chunk size of same characters ; Add / subtract pow ( chunkSize , 2 ) depending upon character ; Return the score ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int calcScore ( string str ) { int score = 0 ; int len = str . length ( ) ; for ( int i = 0 ; i < len ; ) { int chunkSize = 1 ; char currentChar = str [ i ++ ] ; while ( i < len && str [ i ] == currentChar ) { chunkSize ++ ; i ++ ; } if ( currentChar == '1' ) score += pow ( chunkSize , 2 ) ; else score -= pow ( chunkSize , 2 ) ; } return score ; } int main ( ) { string str = "11011" ; cout << calcScore ( str ) ; return 0 ; }