#include <iostream>
using namespace std;
string largerString(string a, string b) {
int idxa = 0;
int idxb = 0;
while (idxa<a.size() && a[idxa] == '0') {
idxa++;
}
while (idxb < b.size() && b[idxb] == '0') {
idxb++;
}
a.erase(0, idxa);
b.erase(0, idxb);
if (a.size() > b.size()) return a;
else if (b.size() > a.size()) return b;
else {
for (size_t i = 0; i < a.size(); i++)
{
if (a[i] > b[i]) return a;
if (b[i] > a[i]) return b;
}
}
return a;
}
bool validString(string s) {
for (size_t i = 0; i < s.size(); i++)
{
if (s[i] != '0') return true;
}
return false;
}
string RemoveWorstChar(string input, int divBranch) {
int changeVal1 = -10;
int lr1 = 100'001;
int lr1Index = -1;
for (size_t j = 0; j < input.size(); j++)
{
int val = input[j] - '0';
if (val % 3 == divBranch) {
if (j == input.size() - 1) {
if (changeVal1 < 0) {
lr1 = 1;
lr1Index = j;
changeVal1 = 0;
}
}
for (size_t k = j + 1; k < input.size(); k++)
{
if (j > 0 || input[k] != '0') {
int curlr = k - j;
int curCV = input[k] - input[j];
if (curlr == 1 && curCV > 0) {
changeVal1 = curCV;
lr1 = 1;
lr1Index = j;
j = input.size();
k = input.size();
}
else if (curlr < lr1) {
lr1 = curlr;
changeVal1 = curCV;
lr1Index = j;
}
else if (curlr == lr1 && curCV >= changeVal1) {
changeVal1 = curCV;
lr1Index = j;
}
break;
}
else if (k == input.size() - 1 && lr1 == 100'001) return "0";
}
}
//cout << lr1Index << " " << changeVal1 << " " << lr1 << "\n";
}
if (lr1 != 100'001) {
input.erase(lr1Index, lr1);
}
return input;
}
int main()
{
int a;
cin >> a;
for (size_t i = 0; i < a; i++)
{
string input;
cin >> input;
int inpSum = 0;
int oneLeft = 0;
int twoLeft = 0;
for (size_t j = 0; j < input.size(); j++)
{
inpSum += input[j] - '0';
if (input[j] % 3 == 1) oneLeft++;
else if (input[j] % 3 == 2) twoLeft++;
}
inpSum %= 3;
// 0
if (inpSum == 0) {
cout << input << "\n";
continue;
}
// 1
if (inpSum == 1) {
string res1 = "0";
string res2 = "0";
if (oneLeft > 0) {
res1 = RemoveWorstChar(input, 1);
}
//1.2
if (twoLeft > 1 && input.size()-res1.size()>1) {
res2 = RemoveWorstChar(input, 2);
res2 = RemoveWorstChar(res2, 2);
}
string sol = largerString(res1, res2);
if (validString(sol)) cout << sol << "\n";
else cout << "-1\n";
}
// 2
if (inpSum == 2) {
string res1 = "0";
string res2 = "0";
if (twoLeft > 0) {
res1 = RemoveWorstChar(input, 2);
}
//1.2
if (oneLeft > 1 && input.size() - res1.size() > 1) {
res2 = RemoveWorstChar(input, 1);
res2 = RemoveWorstChar(res2, 1);
}
string sol = largerString(res1, res2);
if (validString(sol)) cout << sol << "\n";
else cout << "-1\n";
}
}
}