You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.

Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.


-----Input-----

The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 10^6 characters.


-----Output-----

Print a number in the decimal notation without leading zeroes — the result of the permutation.

If it is impossible to rearrange the digits of the number a in the required manner, print 0.


-----Examples-----
Input
1689

Output
1869

Input
18906

Output
18690

Difficulty: competition

Starter code:

Solutions:
def end(x) :
    if x == 0 :
        return "1869";
    if x == 6 :
        return "1968";
    if x == 5 :
        return "1689";
    if x == 4 :
        return "6891";
    if x == 3 :
        return  "1689";
    if x == 2 :
        return  "1986";
    if x == 1 :
        return  "1896";

d = [0] * 10;
for c in input() :
    d[int(c)] += 1;
for i in [1,6,8,9] :
    d[i] -= 1;

s = "";
ost = 0;

for i in range(10) :
    for j in range(d[i]):
        ost = (ost * 10 + i) % 7;

ost = (1869, 1896, 1986, 1698, 6198, 1689, 1968)[ost * 10000 % 7];

for c in (1,2,3,4,5,6,7,8,9) :
    s += str(c) * d[c];

print((s + str(ost) + "0" * d[0]));


def end(x) :
    if x == 0 :
        return "1869";
    if x == 6 :
        return "1968";
    if x == 5 :
        return "1689";
    if x == 4 :
        return "6891";
    if x == 3 :
        return  "1698";
    if x == 2 :
        return  "1986";
    if x == 1 :
        return  "1896";

d = [0] * 10;
for c in input() :
    d[int(c)] += 1;
for i in [1,6,8,9] :
    d[i] -= 1;

s = "";
ost = 0;

for i in range(10) :
    for j in range(d[i]):
        ost = (ost * 10 + i) % 7;

ost = ost * 10000 % 7;

for c in (1,2,3,4,5,6,7,8,9) :
    s += str(c) * d[c];

print((s + end(ost) + "0" * d[0]));


from itertools import permutations

t, r = [0, 1, 4, 6, 5, 2], {i: 0 for i in '0123456789'}
for i in input(): r[i] += 1
for i in '1689': r[i] -= 1

s = a = b = 0
for i in '9876543210':
    a, b = b, (b + r[i]) % 6
    s += int(i) * (t[b]	- t[a])
d = pow(10, b, 7)

for q in permutations('1689'):
    q = ''.join(q)
    if (s + d * int(q)) % 7 == 0:
        print(q + ''.join(i * r[i] for i in '0123456789'))
        break

p, t = {}, input()
for i in '0123456789': p[i] = 0
for i in t: p[i] += 1
for i in '1689': p[i] -= 1

q = [0] * 7
r = pow(10, (len(t) - 4) % 6, 7)
for i, j in enumerate([9681, 6819, 6981, 6891, 8691, 9861, 1896]): q[(i * r) % 7] = j

s = [0] + [int('1' * i) % 7 for i in range(1, 6)]
a = b = d = 0
for i in '0123456789':
    b = (a + p[i]) % 6
    d -= ((s[b] - s[a]) * int(i)) % 7
    a = b

print(str(q[d % 7]) + ''.join(i * p[i] for i in '9876543210'))

S='1689'
s=input()
Z=s.count('0')
s=s.replace('0','')
for i in S:t=s.index(i);s=s[:t]+s[t+1:]
k=0
for i in s:k=(k*10+ord(i)-ord('0'))%7
for a in S:
    for b in S:
        for c in S:
            for d in S:
                if len(set(a+b+c+d))==4 and (k*10000+int(a+b+c+d))%7==0:
                    print(s+a+b+c+d+'0'*Z)
                    return

def main():
    a = input()
    l = len(a)
    book = [0] * 128
    a = list(a)
    for i in range (l):
        a[i] = chr(ord(a[i]) - ord('0'))
        book[ord(a[i])] += 1
    num = 0
    m = 0
    buf = []
    for i in range (1,10):
        if i in (1, 8, 6, 9):
            for j in range (1, book[i]):
                buf.append(i)
                m = (10 * m + i) % 7
                num += 1
        else:
            for j in range (1,book[i]+1):
                buf.append(i)
                m = (10 * m + i) % 7
                num += 1
    m = ( m * 10000 ) % 7
    mp = [9681, 1896,9861, 1698, 6891, 6981, 6819]
    buf.append(mp[m])
    num += 4
    buf.append('0' * (l - num))
    print(''.join(map(str, buf)))

main()



# Made By Mostafa_Khaled 
bot = True 
a=input()

cnt=[0]*10

for i in (1,6,8,9):

	cnt[i]=-1

for i in a:

	cnt[int(i)]+=1

mod = [1869, 1968, 9816, 6198, 1698, 1986, 1896, 1869]

modCnt=0

for i in range(1,10):

	for j in range(cnt[i]):

		modCnt= (modCnt*3 + i)%7

	print(str(i)*cnt[i], end='')

modCnt=(10000*modCnt)%7

print(str(mod[7-modCnt])+'0'*cnt[0])

# Made By Mostafa_Khaled

s=input()
cnt=[0]*10
for c in s:
    cnt[int(c)]+=1

if cnt[1]==1 and cnt[6]==1 and cnt[8]==1 and cnt[9]==1 and sum(cnt)==cnt[0]+4:
    print('9618'+'0'*cnt[0])
else:

    cnt[1]-=1
    cnt[6]-=1
    cnt[8]-=1
    cnt[9]-=1

    s=[]
    mod=0
    for d in range(1,10):
        for i in range(cnt[d]):
            s+=[str(d)]
            mod*=10
            mod+=d
            mod%=7

    import itertools
    a=[1,6,8,9]
    for p in itertools.permutations(a):
        x=p[0]*1000+p[1]*100+p[2]*10+p[3]
        if (mod*10000+x)%7==0:
            res=''.join(s)
            res+=str(x)+'0'*cnt[0]
            print(res)
            break

import sys
from math import *
from fractions import gcd
readints=lambda:list(map(int, input().strip('\n').split()))

n=input().strip('\n')

from itertools import permutations
perms = [''.join(p) for p in permutations('1689')]
mod={}
for p in perms:
    p=int(p)
    mod[p%7]=p


freq=[0]*10
for d in n:
    d=int(d)
    freq[d]+=1

    
for d in (1,6,8,9):
    freq[d]-=1

m=0
for i in range(1,10):
    for _ in range(freq[i]):
        m=(10*m + i)%7

suf=''
for p in list(mod.values()):
    cur=int(str(m)+str(p))
    if cur%7==0:
        suf=str(p)
        break

ans=''
for i in range(1,10):
    ans += str(i)*freq[i]

ans += suf
ans += '0'*freq[0]

print(ans)


n = [int(d) for d in input()]
for x in [1,6,8,9]:
	for i in range(len(n)):
		if n[i]==x:
			del n[i]
			break
prefix = [1869,6189,1689,6198,1698,9861,1896]
L = sum([n[i]*pow(10,len(n)-i-1,7) for i in range(len(n))])%7
print(prefix[(-L)*pow(10,5*len(n),7)%7],end='')
print(*n, sep='')

import sys
n = [int(d) for d in sys.stdin.readline()[:-1]]
for x in [1,6,8,9]:
	for i in range(len(n)):
		if n[i]==x:
			del n[i]
			break
prefix = [1869,6189,1689,6198,1698,9861,1896]
L = sum([n[i]*pow(10,len(n)-i-1,7) for i in range(len(n))])%7
print(prefix[(-L)*pow(10,5*len(n),7)%7],end='')
print(*n, sep='')

ans=[1,6,8,9]
rem=[]
from collections import *
al=defaultdict(int)
for i in range(len(ans)):
    for j in range(len(ans)):
        for m in range(len(ans)):
            for t in range(len(ans)):
                re=[i,j,m,t]
                if(len(set(re))==4):
                    q=pow(10,3)*ans[i]+(pow(10,2)*ans[j])+(pow(10,1)*ans[m])+(ans[t])
                    if(al[q%7]==0):
                        
                        rem.append([q%7,q])
                       
                        al[q%7]=1

s=input()
rem.sort()
ans=[]
for i in range(len(s)):
    ans.append(int(s[i]))
count=0
ans.remove(1)
ans.remove(6)
ans.remove(8)
ans.remove(9)
i=0

while(i<len(ans)):
   
    if(i==0):
        while(i<len(ans) and ans[i]==0):
            count+=1
            i+=1
        i+=1
    else:
        i+=1
temp=[]
for i in range(count,len(ans)):
    temp.append(ans[i])
fin=0
if(len(temp)==0):
    s=str(rem[0][1])+'0'*count
    print(s)
    return
else:
    for i in range(len(temp)):
        fin=fin+(pow(10,len(temp)-i-1,7)*(temp[i]%7)%7)
        fin%=7
  
    if(fin==0):
        m=''.join(map(str,temp))+str(rem[fin][1])+('0'*count)
    if(fin==1):
         m=''.join(map(str,temp))+str(rem[3][1])+('0'*count)
    if(fin==2):
         m=''.join(map(str,temp))+str(rem[6][1])+('0'*count)

    if(fin==3):
        m=''.join(map(str,temp))+str(rem[2][1])+('0'*count)
    if(fin==4):
        m=''.join(map(str,temp))+str(rem[5][1])+('0'*count)
    if(fin==5):
        m=''.join(map(str,temp))+str(rem[1][1])+('0'*count)
    if(fin==6):
        m=''.join(map(str,temp))+str(rem[4][1])+('0'*count)
        
        
    print(m)
    
        
        
    
    


ans=[1,6,8,9]
rem=[]
from collections import *
al=defaultdict(int)
for i in range(len(ans)):
    for j in range(len(ans)):
        for m in range(len(ans)):
            for t in range(len(ans)):
                re=[i,j,m,t]
                if(len(set(re))==4):
                    q=pow(10,3)*ans[i]+(pow(10,2)*ans[j])+(pow(10,1)*ans[m])+(ans[t])
                    if(al[q%7]==0):
                        
                        rem.append([q%7,q])
                       
                        al[q%7]=1
 
s=input()
rem.sort()
ans=[]
for i in range(len(s)):
    ans.append(int(s[i]))
count=0
ans.remove(1)
ans.remove(6)
ans.remove(8)
ans.remove(9)
i=0
 
while(i<len(ans)):
   
    if(i==0):
        while(i<len(ans) and ans[i]==0):
            count+=1
            i+=1
        i+=1
    else:
        i+=1
temp=[]
for i in range(count,len(ans)):
    temp.append(ans[i])
fin=0
if(len(temp)==0):
    s=str(rem[0][1])+'0'*count
    print(s)
    return
else:
    for i in range(len(temp)):
        fin=fin+(pow(10,len(temp)-i-1,7)*(temp[i]%7)%7)
        fin%=7
  
    if(fin==0):
        m=''.join(map(str,temp))+str(rem[fin][1])+('0'*count)
    if(fin==1):
         m=''.join(map(str,temp))+str(rem[3][1])+('0'*count)
    if(fin==2):
         m=''.join(map(str,temp))+str(rem[6][1])+('0'*count)
 
    if(fin==3):
        m=''.join(map(str,temp))+str(rem[2][1])+('0'*count)
    if(fin==4):
        m=''.join(map(str,temp))+str(rem[5][1])+('0'*count)
    if(fin==5):
        m=''.join(map(str,temp))+str(rem[1][1])+('0'*count)
    if(fin==6):
        m=''.join(map(str,temp))+str(rem[4][1])+('0'*count)
        
        
    print(m)
    


p, t = {}, input()
for i in '0123456789': p[i] = 0
for i in t: p[i] += 1
for i in '1689': p[i] -= 1
 
q = [0] * 7
r = pow(10, (len(t) - 4) % 6, 7)
for i, j in enumerate([9681, 6819, 6981, 6891, 8691, 9861, 1896]): q[(i * r) % 7] = j
 
s = [0] + [int('1' * i) % 7 for i in range(1, 6)]
a = b = d = 0
for i in '0123456789':
    b = (a + p[i]) % 6
    d -= ((s[b] - s[a]) * int(i)) % 7
    a = b
 
print(str(q[d % 7]) + ''.join(i * p[i] for i in '9876543210'))

import os
import sys
from io import BytesIO, IOBase


def main():
    pass


# region fastio

BUFSIZE = 8192


class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")


def binary(n):
    return (bin(n).replace("0b", ""))


def decimal(s):
    return (int(s, 2))


def pow2(n):
    p = 0
    while (n > 1):
        n //= 2
        p += 1
    return (p)


def isPrime(n):
    if (n == 1):
        return (False)
    else:
        root = int(n ** 0.5)
        root += 1
        for i in range(2, root):
            if (n % i == 0):
                return (False)
        return (True)
s=input()
f=[0]*10
mod=[1869,8961,6981,6198,1698,9861,1896]
for i in s:
    f[int(i)]+=1
a=""
cm=0
for i in s:
    if(i!="0"):
        n=int(i)
        if(n==1 or n==6 or n==8 or n==9):
            if(f[n]>1):
                cm=(cm*10+n)%7
                f[n]-=1
                print(i,end="")
        else:
            cm=(cm*10+n)%7
            f[n]-=1
            print(i,end="")
#print(a,cm)
for i in range(0,4):
    cm=(cm*10)%7
if(cm==0):
    print(str(mod[cm]),end="")
    print('0'*f[0])
else:
    print(str(mod[7-cm]), end="")
    print('0' * f[0])

'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd 
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
def ceil(a,b): return (a+b-1)//b
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
# mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')


test = 0
def solve():

    # int( str(i)+x[i] ) is divisible by 7
    x = ['1869','6198','1896','1689','1986','1968','8691']
    freq = [0]*10
    s = si()
    for i in s:
        freq[int(i)] +=1

    freq[1] -= 1
    freq[6] -= 1
    freq[8] -= 1
    freq[9] -= 1

    res = ""
    cur = 0
    for i in range(1,10):
        for j in range(freq[i]):
            cur *= 10
            cur += i
            cur %= 7
    for i in range(1,10):
        print(str(i)*freq[i],end="")
    print(x[cur],end="")
    
    print('0'*freq[0])


    
    
        



          
def __starting_point():

   
    if path.exists('input.txt'):
        sys.stdin=open('input.txt', 'r')
        sys.stdout=open('output.txt','w')
    else:
        input=sys.stdin.readline

    t = 1
    if test:
        t = ii()

    for _ in range(t):

        solve()
__starting_point()

# by the authority of GOD     author: manhar singh sachdev #

import os,sys
from io import BytesIO, IOBase

def main():
    x = input().strip()
    ls = []
    fl = [0,0,0,0]
    st = '1689'
    for i in x:
        if i in st and not fl[st.index(i)]:
            fl[st.index(i)] = 1
            continue
        ls.append(i)
    ls1 = ls[::-1]
    perm = ['1869','1968','1689','6198','1698','1986','1896']
    val = [1,3,2,6,4,5]
    rem = 0
    for i in range(len(ls1)):
        rem += (int(ls1[i])*val[i%6])%7
        rem %= 7
    ls = list(perm[((7-rem)*pow(pow(10,len(ls1),7),5,7))%7])+ls
    print(''.join(ls))

#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def __starting_point():
    main()
__starting_point()

# Legends Always Come Up with Solution
# Author: Manvir Singh

import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict,deque,Counter
from bisect import *
from math import sqrt,pi,ceil,log
import math
from itertools import permutations
from copy import deepcopy

from sys import setrecursionlimit


def main():
    a=input().rstrip()
    n=len(a)
    a=Counter(a)
    a["6"]-=1
    a["1"]-=1
    a["8"]-=1
    a["9"]-=1
    z,s,y=0,[],[1]
    for i in range(n):
        y.append((y[-1]*10)%7)
    xx=1
    for i in a:
        if i!="0":
            x=int(i)
            for j in range(a[i]):
                s.append(i)
                z=(z+x*y[n-xx])%7
                xx+=1
    f=1
    for i in permutations([1,6,8,9]):
        if (z+i[0]*y[n-xx]+i[1]*y[n-xx-1]+i[2]*y[n-xx-2]+i[3]*(y[n-xx-3]))%7==0:
            f=0
            s.extend([str(i[0]),str(i[1]),str(i[2]),str(i[3])])
            break
    if f:
        print(0)
    else:
        s.append("0"*a["0"])
        print("".join(s))

# region fastio
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)


class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")


sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

def __starting_point():
    main()
__starting_point()