//tonynater - CodeChef 2013
#include <algorithm>
#include <assert.h>
#include <bitset>
#include <cassert>
#include <climits>
#include <cmath>
#include <complex>
#include <ctime>
#include <ctype.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
using namespace std;
#define sz(x) ((int) x.size())
typedef long double ld;
typedef long long ll;
typedef pair<int, int> pii;
const double pi = acos(-1);
const double tau = 2*pi;
const double epsilon = 1e-6;
const int MAX_STRING = 100100;
int T;
int N;
string S;
int nxt[MAX_STRING];
int prv[MAX_STRING];
vector<pii> curinterests;
vector<pii> newinterests;
int main (int argc, const char * argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(NULL);
cin >> T;
for(int t = 0; t < T; t++)
{
cin >> N >> S;
for(int i = 0; i < N-1; i++)
nxt[i] = i+1;
nxt[N-1] = -1;
for(int i = 0; i < N; i++)
prv[i] = i-1;
curinterests.clear();
for(int i = 0; i < N-1; i++)
if(S[i] == '4' && S[i+1] == '7')
curinterests.push_back(pii(i,i));
ll P = 0;
while(sz(curinterests) > 0)
{
newinterests.clear();
for(int i = 0, nRemoved = 0; i < sz(curinterests); i++, ++nRemoved)
{
P += curinterests[i].second+1;
if(prv[curinterests[i].first] == -1 && nxt[nxt[curinterests[i].first]] != -1)
{
prv[nxt[nxt[curinterests[i].first]]] = prv[curinterests[i].first];
continue;
}
if(prv[curinterests[i].first] != -1 && nxt[nxt[curinterests[i].first]] == -1)
{
nxt[prv[curinterests[i].first]] = nxt[nxt[curinterests[i].first]];
continue;
}
if(prv[curinterests[i].first] == -1 && nxt[nxt[curinterests[i].first]] == -1) continue;
nxt[prv[curinterests[i].first]] = nxt[nxt[curinterests[i].first]];
prv[nxt[nxt[curinterests[i].first]]] = prv[curinterests[i].first];
if(S[prv[curinterests[i].first]] == '4' && S[nxt[nxt[curinterests[i].first]]] == '7')
newinterests.push_back(pii(prv[curinterests[i].first], curinterests[i].second-1-2*nRemoved));
}
curinterests.clear();
for(int i = 0; i < sz(newinterests); i++)
curinterests.push_back(newinterests[i]);
}
cout << P << '\n';
}
return 0;
}