t = Integer(gets)
while t > 0
a4 = []
a7 = []
n = Integer(gets)
i = 1

while i <= n 
a4 << i.to_s.count("4")
a7 << i.to_s.count("7")

i = i + 1
end
count = 0 
i = 1
while ( i<=n)
if a4[i-1] == a7[i-1]
count = count + 1
else
break
end

i =i + 1
end

count = count*(count+1)/2
j = i
while ( i<=n)
if a4[i-1] != a7[i-1]
break
end
i = i + 1
end
count = count + j
print "#{count}\n" 
t = t - 1
end