#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned n;
    scanf("%u", &n);

    if (n == 1) {
        scanf("%u", &n);
        printf("%u\n", n);
        return 0;
    }

    unsigned *a = malloc(n * sizeof(int));
    scanf("%u", &a[0]);
    unsigned max = a[0];
    for (int i = 1; i < n; i++) {
        scanf("%u", &a[i]);
        if (a[i] > max) {
            max = a[i];
        }
    }
    unsigned len = 0;
    while (max) {
        len += 1;
        max >>= 1;
    }
    for (int k = len - 1; k >= 0; k--) {
        unsigned shift = 1<<k;
        unsigned countOf1bit = 0;
        unsigned indexSave;
        for (int i = 0; i < n; i++) {
            if (shift & a[i]) {
                if (!countOf1bit) {
                    indexSave = i;
                    countOf1bit++;
                } else {
                    countOf1bit++;
                    break;
                }
            }
        }
        if (countOf1bit == 1) {
            printf("%u ", a[indexSave]);
            for (int i = 0; i < indexSave; i++) {
                printf("%u ", a[i]);
            }
            for (int i = indexSave + 1; i < n; i++) {
                printf("%u ", a[i]);
            free(a);
            return 0;
            }
        }
    }

    for (int i = 0; i < n; i++) {
        printf("%u ", a[i]);
    }

    free(a);
    return 0;
}


#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned n;
    scanf("%u", &n);

    if (n == 1) {
        scanf("%u", &n);
        printf("%u\n", n);
        return 0;
    }

    unsigned *a = malloc(n * sizeof(int));
    scanf("%u", &a[0]);
    unsigned max = a[0];
    for (int i = 1; i < n; i++) {
        scanf("%u", &a[i]);
        if (a[i] > max) {
            max = a[i];
        }
    }
    unsigned len = 0;
    while (max) {
        len += 1;
        max >>= 1;
    }
    for (int k = len - 1; k >= 0; k--) {
        unsigned shift = 1<<k;
        unsigned countOf1bit = 0;
        unsigned indexSave;
        for (int i = 0; i < n; i++) {
            if (shift & a[i]) {
                if (!countOf1bit) {
                    indexSave = i;
                    countOf1bit++;
                } else {
                    countOf1bit++;
                    break;
                }
            }
        }
        if (countOf1bit == 1) {
            printf("%u ", a[indexSave]);
            for (int i = 0; i < indexSave; i++) {
                printf("(%d < %d)", i, n);
                printf("%u ", a[i]);
            }
            for (int i = indexSave + 1; i <= n; i++) {
                printf("(%d < %d)", i, n);
                printf("%u ", a[i]);
            }
            free(a);
            return 0;
        }
    }

    for (int i = 0; i < n; i++) {
        printf("%u ", a[i]);
    }

    free(a);
    return 0;
}


#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned n;
    scanf("%u", &n);

    if (n == 1) {
        scanf("%u", &n);
        printf("%u\n", n);
        return 0;
    }

    unsigned *a = malloc(n * sizeof(int));
    scanf("%u", &a[0]);
    unsigned max = a[0];
    for (int i = 1; i < n; i++) {
        scanf("%u", &a[i]);
        if (a[i] > max) {
            max = a[i];
        }
    }
    unsigned len = 0;
    while (max) {
        len += 1;
        max >>= 1;
    }
    for (int k = len - 1; k >= 0; k--) {
        unsigned shift = 1<<k;
        unsigned countOf1bit = 0;
        unsigned indexSave;
        for (int i = 0; i < n; i++) {
            if (shift & a[i]) {
                if (!countOf1bit) {
                    indexSave = i;
                    countOf1bit++;
                } else {
                    countOf1bit++;
                    break;
                }
            }
        }
        if (countOf1bit == 1) {
            printf("%u ", a[indexSave]);
            for (int i = 0; i < indexSave; i++) {
                printf("%u ", a[i]);
            }
            for (int i = indexSave + 1; i < n; i++) {
                printf("%u ", a[i]);
            }
            free(a);
            return 0;
        }
    }

    for (int i = 0; i < n; i++) {
        printf("%u ", a[i]);
    }

    free(a);
    return 0;
}


#include <stdio.h>
#include <stdlib.h>

int main()
{
    unsigned n;
    scanf("%u", &n);

    if (n == 1) {
        scanf("%u", &n);
        printf("%u\n", n);
        return 0;
    }

    unsigned *a = malloc(n * sizeof(int));
    scanf("%u", &a[0]);
    unsigned max = a[0];
    for (int i = 1; i < n; i++) {
        scanf("%u", &a[i]);
        if (a[i] > max) {
            max = a[i];
        }
    }
    unsigned len = 0;
    while (max) {
        len += 1;
        max >>= 1;
    }
    for (int k = len - 1; k >= 0; k--) {
        unsigned shift = 1<<k;
        unsigned countOf1bit = 0;
        unsigned indexSave;
        for (int i = 0; i < n; i++) {
            if (shift & a[i]) {
                if (!countOf1bit) {
                    indexSave = i;
                    countOf1bit++;
                } else {
                    countOf1bit++;
                    break;
                }
            }
        }
        if (countOf1bit == 1) {
            printf("%u ", a[indexSave]);
            for (int i = 0; i < indexSave; i++) {
                printf("%u ", a[i]);
            }
            for (int i = indexSave + 1; i <= n; i++) {
                printf("%u ", a[i]);
            }
            free(a);
            return 0;
        }
    }

    for (int i = 0; i < n; i++) {
        printf("%u ", a[i]);
    }

    free(a);
    return 0;
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Template;
using SC = Scanner;

public partial class Solver
{
    public void Solve()
    {
        var N = sc.Int;
        var A = sc.ArrInt;
        Array.Sort(A);
        swap(ref A[0], ref A[N - 1]);
        for (int i = N - 1; i > 1; i--) swap(ref A[i], ref A[i - 1]);
        Console.WriteLine(string.Join(" ", A));
    }
}

#region Template
public partial class Solver
{
    public SC sc = new SC();
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        var sol = new Solver();
        int testcase = 1;
        //testcase = sol.sc.Int;
        //var th = new Thread(sol.Solve, 1 << 26);th.Start();th.Join();
        while (testcase-- > 0)
            sol.Solve();
        Console.Out.Flush();
    }
}
public static class Template
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; }
    public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; }
    public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; }
    public static void Out<T>(this IList<T> A, out T a) => a = A[0];
    public static void Out<T>(this IList<T> A, out T a, out T b) { a = A[0]; b = A[1]; }
    public static void Out<T>(this IList<T> A, out T a, out T b, out T c) { A.Out(out a, out b); c = A[2]; }
    public static void Out<T>(this IList<T> A, out T a, out T b, out T c, out T d) { A.Out(out a, out b, out c); d = A[3]; }
    public static string Concat<T>(this IEnumerable<T> A, string sp) => string.Join(sp, A);
    public static char ToChar(this int s, char begin = '0') => (char)(s + begin);
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid());
    public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; }
    public static string ToStr<T>(this T[][] A) => A.Select(a => a.Concat(" ")).Concat("\n");
    public static int ArgMax<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; }
    public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; }
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}
public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
    public void Make<T1, T2, T3, T4, T5, T6, T7>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6, out T7 v7) { Make(out v1, out v2, out v3, out v4, out v5, out v6); v7 = Next<T7>(); }
    public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); }
    public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); }
    public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); }
}

#endregion


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Runtime.CompilerServices;
using System.Text;
using System.Diagnostics;
using System.Numerics;
using static System.Console;
using static System.Convert;
using static System.Math;
using static Template;
using SC = Scanner;

public partial class Solver
{
    public void Solve()
    {
        var N = sc.Int;
        var A = sc.ArrInt;
        var ct = new int[31];
        for(int i = 0; i < N; i++)
        {
            for (int j = 0; j < 31; j++)
                if ((1 & A[i] >> j) == 1) ct[j]++;
        }
        var res = 0L;int idx = 0;
        for(int i = 0; i < N; i++)
        {
            var calc = 0L;
            for (int j = 0; j < 31; j++)
                calc += ToInt64(ct[j] == 1) * (1 & A[i] >> j) * (1L << j);
            if (chmax(ref res, calc)) idx = i;

        }
        var r = new List<int> { A[idx] };
        for (int i = 0; i < N; i++)
        {
            if (i != idx) r.Add(A[i]);
        }
        Console.WriteLine(string.Join(" ", r));
    }
}

#region Template
public partial class Solver
{
    public SC sc = new SC();
    static void Main(string[] args)
    {
        Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false });
        var sol = new Solver();
        int testcase = 1;
        //testcase = sol.sc.Int;
        //var th = new Thread(sol.Solve, 1 << 26);th.Start();th.Join();
        while (testcase-- > 0)
            sol.Solve();
        Console.Out.Flush();
    }
}
public static class Template
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmin<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) > 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static bool chmax<T>(ref T a, T b) where T : IComparable<T> { if (a.CompareTo(b) < 0) { a = b; return true; } return false; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(ref T a, ref T b) { var t = b; b = a; a = t; }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void swap<T>(this IList<T> A, int i, int j) { var t = A[i]; A[i] = A[j]; A[j] = t; }
    public static T[] Create<T>(int n, Func<T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(); return rt; }
    public static T[] Create<T>(int n, Func<int, T> f) { var rt = new T[n]; for (var i = 0; i < rt.Length; ++i) rt[i] = f(i); return rt; }
    public static void Out<T>(this IList<T> A, out T a) => a = A[0];
    public static void Out<T>(this IList<T> A, out T a, out T b) { a = A[0]; b = A[1]; }
    public static void Out<T>(this IList<T> A, out T a, out T b, out T c) { A.Out(out a, out b); c = A[2]; }
    public static void Out<T>(this IList<T> A, out T a, out T b, out T c, out T d) { A.Out(out a, out b, out c); d = A[3]; }
    public static string Concat<T>(this IEnumerable<T> A, string sp) => string.Join(sp, A);
    public static char ToChar(this int s, char begin = '0') => (char)(s + begin);
    public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> A) => A.OrderBy(v => Guid.NewGuid());
    public static int CompareTo<T>(this T[] A, T[] B, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; for (var i = 0; i < Min(A.Length, B.Length); i++) { int c = cmp(A[i], B[i]); if (c > 0) return 1; else if (c < 0) return -1; } if (A.Length == B.Length) return 0; if (A.Length > B.Length) return 1; else return -1; }
    public static string ToStr<T>(this T[][] A) => A.Select(a => a.Concat(" ")).Concat("\n");
    public static int ArgMax<T>(this IList<T> A, Comparison<T> cmp = null) { cmp = cmp ?? Comparer<T>.Default.Compare; T max = A[0]; int rt = 0; for (int i = 1; i < A.Count; i++) if (cmp(max, A[i]) < 0) { max = A[i]; rt = i; } return rt; }
    public static T PopBack<T>(this List<T> A) { var v = A[A.Count - 1]; A.RemoveAt(A.Count - 1); return v; }
    public static void Fail<T>(T s) { Console.WriteLine(s); Console.Out.Close(); Environment.Exit(0); }
}
public class Scanner
{
    public string Str => Console.ReadLine().Trim();
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public int[] ArrInt => Str.Split(' ').Select(int.Parse).ToArray();
    public long[] ArrLong => Str.Split(' ').Select(long.Parse).ToArray();
    public char[][] Grid(int n) => Create(n, () => Str.ToCharArray());
    public int[] ArrInt1D(int n) => Create(n, () => Int);
    public long[] ArrLong1D(int n) => Create(n, () => Long);
    public int[][] ArrInt2D(int n) => Create(n, () => ArrInt);
    public long[][] ArrLong2D(int n) => Create(n, () => ArrLong);
    private Queue<string> q = new Queue<string>();
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Next<T>() { if (q.Count == 0) foreach (var item in Str.Split(' ')) q.Enqueue(item); return (T)Convert.ChangeType(q.Dequeue(), typeof(T)); }
    public void Make<T1>(out T1 v1) => v1 = Next<T1>();
    public void Make<T1, T2>(out T1 v1, out T2 v2) { v1 = Next<T1>(); v2 = Next<T2>(); }
    public void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3) { Make(out v1, out v2); v3 = Next<T3>(); }
    public void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4) { Make(out v1, out v2, out v3); v4 = Next<T4>(); }
    public void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5) { Make(out v1, out v2, out v3, out v4); v5 = Next<T5>(); }
    public void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6) { Make(out v1, out v2, out v3, out v4, out v5); v6 = Next<T6>(); }
    public void Make<T1, T2, T3, T4, T5, T6, T7>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6, out T7 v7) { Make(out v1, out v2, out v3, out v4, out v5, out v6); v7 = Next<T7>(); }
    public (T1, T2) Make<T1, T2>() { Make(out T1 v1, out T2 v2); return (v1, v2); }
    public (T1, T2, T3) Make<T1, T2, T3>() { Make(out T1 v1, out T2 v2, out T3 v3); return (v1, v2, v3); }
    public (T1, T2, T3, T4) Make<T1, T2, T3, T4>() { Make(out T1 v1, out T2 v2, out T3 v3, out T4 v4); return (v1, v2, v3, v4); }
}

#endregion


using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Math;
using MethodImplAttribute = System.Runtime.CompilerServices.MethodImplAttribute;
using MethodImplOptions = System.Runtime.CompilerServices.MethodImplOptions;

public static class P
{
    public static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        var a = Console.ReadLine().Split().Select(int.Parse).ToArray();
        SegmentTree<int> table = new SegmentTree<int>(a, 0, (x, y) => x | y);
        int max = -1;
        int maxind = -1;
        for (int i = 0; i < a.Length; i++)
        {
            var remain = table.Query(0, i - 1) | table.Query(i + 1, table.Size - 1);
            var res = (a[i] | remain) - remain;
            if (max < res)
            {
                max = res;
                maxind = i;
            }
        }

        Console.WriteLine($"{a[maxind]} {string.Join(" ", a.Where((_, ind) => ind != maxind))}");
    }
}

class SegmentTree<T>
{
    public int Size { get; private set; }
    T Identity;
    T[] Data;
    Func<T, T, T> Merge;
    int LeafCount;

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public SegmentTree(int size, T identity, Func<T, T, T> merge)
    {
        Init(size, identity, merge);
        for (int i = 1; i < Data.Length; i++) Data[i] = identity;
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public SegmentTree(T[] elems, T identity, Func<T, T, T> merge)
    {
        Init(elems.Length, identity, merge);
        elems.CopyTo(Data, LeafCount);
        for (int i = elems.Length + LeafCount; i < Data.Length; i++) Data[i] = identity;
        for (int i = LeafCount - 1; i >= 1; i--) Data[i] = Merge(Data[i << 1], Data[(i << 1) | 1]);
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private void Init(int size, T identity, Func<T, T, T> merge)
    {
        Size = size;
        Identity = identity;
        Merge = merge;
        LeafCount = 1;
        while (LeafCount < size) LeafCount <<= 1;
        Data = new T[LeafCount << 1];
    }

    public T this[int index]
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get { return Data[LeafCount + index]; }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        set { Update(index, value); }
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public void Update(int i, T x) { Data[i += LeafCount] = x; while (0 < (i >>= 1)) Data[i] = Merge(Data[i << 1], Data[(i << 1) | 1]); }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public void Operate(int i, T x) { Data[i += LeafCount] = Merge(Data[i], x); while (0 < (i >>= 1)) Data[i] = Merge(Data[i << 1], Data[(i << 1) | 1]); }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Query(int l, int r)
    {
        T lRes = Identity, rRes = Identity;
        for (l += LeafCount, r += LeafCount; l <= r; l = (l + 1) >> 1, r = (r - 1) >> 1)
        {
            if ((l & 1) == 1) lRes = Merge(lRes, Data[l]); if ((r & 1) == 0) rRes = Merge(Data[r], rRes);
        }
        return Merge(lRes, rRes);
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Math;
using MethodImplAttribute = System.Runtime.CompilerServices.MethodImplAttribute;
using MethodImplOptions = System.Runtime.CompilerServices.MethodImplOptions;

public static class P
{
    public static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        var a = Console.ReadLine().Split().Select(int.Parse).ToArray();
        SegmentTree<int> table = new SegmentTree<int>(a, 0, (x, y) => x | y);
        int max = -1;
        int maxind = -1;
        for (int i = 0; i < a.Length; i++)
        {
            var remain = table.Query(0, i - 1) | table.Query(i + 1, table.Size - 1);
            var res = a[i] | remain - remain;
            if (max < res)
            {
                max = res;
                maxind = i;
            }
        }

        Console.WriteLine($"{a[maxind]} {string.Join(" ", a.Where((_, ind) => ind != maxind))}");
    }
}

class SegmentTree<T>
{
    public int Size { get; private set; }
    T Identity;
    T[] Data;
    Func<T, T, T> Merge;
    int LeafCount;

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public SegmentTree(int size, T identity, Func<T, T, T> merge)
    {
        Init(size, identity, merge);
        for (int i = 1; i < Data.Length; i++) Data[i] = identity;
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public SegmentTree(T[] elems, T identity, Func<T, T, T> merge)
    {
        Init(elems.Length, identity, merge);
        elems.CopyTo(Data, LeafCount);
        for (int i = elems.Length + LeafCount; i < Data.Length; i++) Data[i] = identity;
        for (int i = LeafCount - 1; i >= 1; i--) Data[i] = Merge(Data[i << 1], Data[(i << 1) | 1]);
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private void Init(int size, T identity, Func<T, T, T> merge)
    {
        Size = size;
        Identity = identity;
        Merge = merge;
        LeafCount = 1;
        while (LeafCount < size) LeafCount <<= 1;
        Data = new T[LeafCount << 1];
    }

    public T this[int index]
    {
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        get { return Data[LeafCount + index]; }
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        set { Update(index, value); }
    }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public void Update(int i, T x) { Data[i += LeafCount] = x; while (0 < (i >>= 1)) Data[i] = Merge(Data[i << 1], Data[(i << 1) | 1]); }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public void Operate(int i, T x) { Data[i += LeafCount] = Merge(Data[i], x); while (0 < (i >>= 1)) Data[i] = Merge(Data[i << 1], Data[(i << 1) | 1]); }
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public T Query(int l, int r)
    {
        T lRes = Identity, rRes = Identity;
        for (l += LeafCount, r += LeafCount; l <= r; l = (l + 1) >> 1, r = (r - 1) >> 1)
        {
            if ((l & 1) == 1) lRes = Merge(lRes, Data[l]); if ((r & 1) == 0) rRes = Merge(Data[r], rRes);
        }
        return Merge(lRes, rRes);
    }
}


using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Math;
using MethodImplAttribute = System.Runtime.CompilerServices.MethodImplAttribute;
using MethodImplOptions = System.Runtime.CompilerServices.MethodImplOptions;

public static class P
{
    public static void Main()
    {
        int n = int.Parse(Console.ReadLine());
        var a = Console.ReadLine().Split().Select(int.Parse).ToArray();

        Console.WriteLine(string.Join(" ", a.OrderByDescending(x => x)));
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using static util;
using P = pair<int, int>;

class Program {
    static void Main(string[] args) {
        var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
        var solver = new Solver(sw);
        // var t = new Thread(solver.solve, 1 << 26); // 64 MB
        // t.Start();
        // t.Join();
        solver.solve();
        sw.Flush();
    }
}

class Solver {
    StreamWriter sw;
    Scan sc;
    void Prt(string a) => sw.WriteLine(a);
    void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
    void Prt(params object[] a) => Prt(string.Join(" ", a));
    public Solver(StreamWriter sw) {
        this.sw = sw;
        this.sc = new Scan();
    }

    public void solve() {
        int n = sc.Int;
        var a = sc.IntArr;
        var cnt = new int[31];
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < 31; j++)
            {
                if (((a[i] >> j) & 1) == 1) {
                    ++cnt[j];
                }
            }
        }
        int max = -1;
        int maxi = -1;
        for (int i = 0; i < n; i++)
        {
            int sum = 0;
            for (int j = 0; j < 31; j++)
            {
                if (((a[i] >> j) & 1) == 1 && cnt[j] == 1) {
                    sum |= 1 << j;
                }
            }
            if (max < sum) {
                max = sum;
                maxi = i;
            }
        }
        if (maxi != 0) {
            a.swap(0, maxi);
        }
        Prt(a);

    }
}

class pair<T, U> : IComparable<pair<T, U>> {
    public T v1;
    public U v2;
    public pair() : this(default(T), default(U)) {}
    public pair(T v1, U v2) { this.v1 = v1; this.v2 = v2; }
    public int CompareTo(pair<T, U> a) {
        int c = Comparer<T>.Default.Compare(v1, a.v1);
        return c != 0 ? c : Comparer<U>.Default.Compare(v2, a.v2);
    }
    public override string ToString() => v1 + " " + v2;
    public void Deconstruct(out T a, out U b) { a = v1; b = v2; }
}
static class util {
    public static readonly int M = 1000000007;
    // public static readonly int M = 998244353;
    public static readonly long LM = 1L << 60;
    public static readonly double eps = 1e-11;
    public static void DBG(string a) => Console.Error.WriteLine(a);
    public static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
    public static void DBG(params object[] a) => DBG(string.Join(" ", a));
    public static void Assert(params bool[] conds) {
        foreach (var cond in conds) if (!cond) throw new Exception();
    }
    public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2);
    public static int CompareList<T>(IList<T> a, IList<T> b) where T : IComparable<T> {
        for (int i = 0; i < a.Count && i < b.Count; i++)
            if (a[i].CompareTo(b[i]) != 0) return a[i].CompareTo(b[i]);
        return a.Count.CompareTo(b.Count);
    }
    public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w;
    static readonly int[] dd = { 0, 1, 0, -1 };
    // static readonly string dstring = "RDLU";
    public static P[] adjacents(int i, int j)
        => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).ToArray();
    public static P[] adjacents(int i, int j, int h, int w)
        => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1]))
                                         .Where(p => inside(p.v1, p.v2, h, w)).ToArray();
    public static P[] adjacents(this P p) => adjacents(p.v1, p.v2);
    public static P[] adjacents(this P p, int h, int w) => adjacents(p.v1, p.v2, h, w);
    public static Dictionary<T, int> compress<T>(this IEnumerable<T> a)
        => a.Distinct().OrderBy(v => v).Select((v, i) => new { v, i }).ToDictionary(p => p.v, p => p.i);
    public static Dictionary<T, int> compress<T>(params IEnumerable<T>[] a) => compress(a.Aggregate(Enumerable.Union));
    public static T[] inv<T>(this Dictionary<T, int> dic) {
        var res = new T[dic.Count];
        foreach (var item in dic) res[item.Value] = item.Key;
        return res;
    }
    public static void swap<T>(ref T a, ref T b) where T : struct { var t = a; a = b; b = t; }
    public static void swap<T>(this IList<T> a, int i, int j) where T : struct { var t = a[i]; a[i] = a[j]; a[j] = t; }
    public static T[] copy<T>(this IList<T> a) {
        var ret = new T[a.Count];
        for (int i = 0; i < a.Count; i++) ret[i] = a[i];
        return ret;
    }
    public static void Deconstruct<T>(this IList<T> v, out T a) {
        a = v[0];
    }
    public static void Deconstruct<T>(this IList<T> v, out T a, out T b) {
        a = v[0]; b = v[1];
    }
    public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c) {
        a = v[0]; b = v[1]; c = v[2];
    }
    public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c, out T d) {
        a = v[0]; b = v[1]; c = v[2]; d = v[3];
    }
    public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c, out T d, out T e) {
        a = v[0]; b = v[1]; c = v[2]; d = v[3]; e = v[4];
    }
}

class Scan {
    StreamReader sr;
    public Scan() { sr = new StreamReader(Console.OpenStandardInput()); }
    public Scan(string path) { sr = new StreamReader(path); }
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public string Str => sr.ReadLine().Trim();
    public pair<T, U> Pair<T, U>() {
        T a; U b;
        Multi(out a, out b);
        return new pair<T, U>(a, b);
    }
    public P P => Pair<int, int>();
    public int[] IntArr => StrArr.Select(int.Parse).ToArray();
    public long[] LongArr => StrArr.Select(long.Parse).ToArray();
    public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
    public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
    bool eq<T, U>() => typeof(T).Equals(typeof(U));
    T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
    T cv<T>(string s) => eq<T, int>()    ? ct<T, int>(int.Parse(s))
                       : eq<T, long>()   ? ct<T, long>(long.Parse(s))
                       : eq<T, double>() ? ct<T, double>(double.Parse(s))
                       : eq<T, char>()   ? ct<T, char>(s[0])
                                         : ct<T, string>(s);
    public void Multi<T>(out T a) => a = cv<T>(Str);
    public void Multi<T, U>(out T a, out U b) {
        var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]);
    }
    public void Multi<T, U, V>(out T a, out U b, out V c) {
        var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]);
    }
    public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d) {
        var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]);
    }
    public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e) {
        var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]);
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using System.Text;
using System.Text.RegularExpressions;
using System.Diagnostics;
using static util;
using P = pair<int, int>;

class Program {
    static void Main(string[] args) {
        var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
        var solver = new Solver(sw);
        // var t = new Thread(solver.solve, 1 << 26); // 64 MB
        // t.Start();
        // t.Join();
        solver.solve();
        sw.Flush();
    }
}

class Solver {
    StreamWriter sw;
    Scan sc;
    void Prt(string a) => sw.WriteLine(a);
    void Prt<T>(IEnumerable<T> a) => Prt(string.Join(" ", a));
    void Prt(params object[] a) => Prt(string.Join(" ", a));
    public Solver(StreamWriter sw) {
        this.sw = sw;
        this.sc = new Scan();
    }

    public void solve() {
        int n = sc.Int;
        var a = sc.IntArr;
        Array.Sort(a);
        Array.Reverse(a);
        Prt(a);

    }
}

class pair<T, U> : IComparable<pair<T, U>> {
    public T v1;
    public U v2;
    public pair() : this(default(T), default(U)) {}
    public pair(T v1, U v2) { this.v1 = v1; this.v2 = v2; }
    public int CompareTo(pair<T, U> a) {
        int c = Comparer<T>.Default.Compare(v1, a.v1);
        return c != 0 ? c : Comparer<U>.Default.Compare(v2, a.v2);
    }
    public override string ToString() => v1 + " " + v2;
    public void Deconstruct(out T a, out U b) { a = v1; b = v2; }
}
static class util {
    public static readonly int M = 1000000007;
    // public static readonly int M = 998244353;
    public static readonly long LM = 1L << 60;
    public static readonly double eps = 1e-11;
    public static void DBG(string a) => Console.Error.WriteLine(a);
    public static void DBG<T>(IEnumerable<T> a) => DBG(string.Join(" ", a));
    public static void DBG(params object[] a) => DBG(string.Join(" ", a));
    public static void Assert(params bool[] conds) {
        foreach (var cond in conds) if (!cond) throw new Exception();
    }
    public static pair<T, U> make_pair<T, U>(T v1, U v2) => new pair<T, U>(v1, v2);
    public static int CompareList<T>(IList<T> a, IList<T> b) where T : IComparable<T> {
        for (int i = 0; i < a.Count && i < b.Count; i++)
            if (a[i].CompareTo(b[i]) != 0) return a[i].CompareTo(b[i]);
        return a.Count.CompareTo(b.Count);
    }
    public static bool inside(int i, int j, int h, int w) => i >= 0 && i < h && j >= 0 && j < w;
    static readonly int[] dd = { 0, 1, 0, -1 };
    // static readonly string dstring = "RDLU";
    public static P[] adjacents(int i, int j)
        => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1])).ToArray();
    public static P[] adjacents(int i, int j, int h, int w)
        => Enumerable.Range(0, dd.Length).Select(k => new P(i + dd[k], j + dd[k ^ 1]))
                                         .Where(p => inside(p.v1, p.v2, h, w)).ToArray();
    public static P[] adjacents(this P p) => adjacents(p.v1, p.v2);
    public static P[] adjacents(this P p, int h, int w) => adjacents(p.v1, p.v2, h, w);
    public static Dictionary<T, int> compress<T>(this IEnumerable<T> a)
        => a.Distinct().OrderBy(v => v).Select((v, i) => new { v, i }).ToDictionary(p => p.v, p => p.i);
    public static Dictionary<T, int> compress<T>(params IEnumerable<T>[] a) => compress(a.Aggregate(Enumerable.Union));
    public static T[] inv<T>(this Dictionary<T, int> dic) {
        var res = new T[dic.Count];
        foreach (var item in dic) res[item.Value] = item.Key;
        return res;
    }
    public static void swap<T>(ref T a, ref T b) where T : struct { var t = a; a = b; b = t; }
    public static void swap<T>(this IList<T> a, int i, int j) where T : struct { var t = a[i]; a[i] = a[j]; a[j] = t; }
    public static T[] copy<T>(this IList<T> a) {
        var ret = new T[a.Count];
        for (int i = 0; i < a.Count; i++) ret[i] = a[i];
        return ret;
    }
    public static void Deconstruct<T>(this IList<T> v, out T a) {
        a = v[0];
    }
    public static void Deconstruct<T>(this IList<T> v, out T a, out T b) {
        a = v[0]; b = v[1];
    }
    public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c) {
        a = v[0]; b = v[1]; c = v[2];
    }
    public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c, out T d) {
        a = v[0]; b = v[1]; c = v[2]; d = v[3];
    }
    public static void Deconstruct<T>(this IList<T> v, out T a, out T b, out T c, out T d, out T e) {
        a = v[0]; b = v[1]; c = v[2]; d = v[3]; e = v[4];
    }
}

class Scan {
    StreamReader sr;
    public Scan() { sr = new StreamReader(Console.OpenStandardInput()); }
    public Scan(string path) { sr = new StreamReader(path); }
    public int Int => int.Parse(Str);
    public long Long => long.Parse(Str);
    public double Double => double.Parse(Str);
    public string Str => sr.ReadLine().Trim();
    public pair<T, U> Pair<T, U>() {
        T a; U b;
        Multi(out a, out b);
        return new pair<T, U>(a, b);
    }
    public P P => Pair<int, int>();
    public int[] IntArr => StrArr.Select(int.Parse).ToArray();
    public long[] LongArr => StrArr.Select(long.Parse).ToArray();
    public double[] DoubleArr => StrArr.Select(double.Parse).ToArray();
    public string[] StrArr => Str.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
    bool eq<T, U>() => typeof(T).Equals(typeof(U));
    T ct<T, U>(U a) => (T)Convert.ChangeType(a, typeof(T));
    T cv<T>(string s) => eq<T, int>()    ? ct<T, int>(int.Parse(s))
                       : eq<T, long>()   ? ct<T, long>(long.Parse(s))
                       : eq<T, double>() ? ct<T, double>(double.Parse(s))
                       : eq<T, char>()   ? ct<T, char>(s[0])
                                         : ct<T, string>(s);
    public void Multi<T>(out T a) => a = cv<T>(Str);
    public void Multi<T, U>(out T a, out U b) {
        var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]);
    }
    public void Multi<T, U, V>(out T a, out U b, out V c) {
        var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]);
    }
    public void Multi<T, U, V, W>(out T a, out U b, out V c, out W d) {
        var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]);
    }
    public void Multi<T, U, V, W, X>(out T a, out U b, out V c, out W d, out X e) {
        var ar = StrArr; a = cv<T>(ar[0]); b = cv<U>(ar[1]); c = cv<V>(ar[2]); d = cv<W>(ar[3]); e = cv<X>(ar[4]);
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace Codeforces
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            long[] a = Console.ReadLine().Split(' ').Select(long.Parse).ToArray();

            byte[] bitCount = new byte[31];
            for (int i = 0; i < a.Length; i++)
            {
                for (byte j = 0; j <= 30; j++)
                {
                    if (bitCount[j] >= 2) continue;
                    long mask = 1L << j;
                    if ((mask & a[i]) != 0)
                        bitCount[j]++;
                }
            }

            long remainBitsMask = 0;
            for(byte j = 0; j <= 30; j++)
            {
                if (bitCount[j] == 1)
                    remainBitsMask |= 1L << j;
            }

            int maxIndex = 0;
            long max = a[0] & remainBitsMask;
            for(int i = 1; i < a.Length; i++)
            {
                long v = a[i] & remainBitsMask;
                if(v > max)
                {
                    maxIndex = i;
                    max = v;
                }
            }

            Console.WriteLine(string.Join(" ", GetResult(a, maxIndex)));
        }

        private static IEnumerable<long> GetResult(long[] a, int maxIndex)
        {
            yield return a[maxIndex];

            for(int i = 0; i < a.Length; i++)
            {
                if (i != maxIndex)
                    yield return a[i];
            }
        }
    }
}


fn read_line() -> String {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).unwrap();
    buffer
}

fn main() {
    let _n = read_line().trim().parse::<u32>().unwrap();

    let line = read_line();
    let arr = line.split(" ").map(|x| x.trim().parse::<u32>().unwrap()).collect::<Vec<_>>();

    let mut v = vec![0; 32];

    for mut a in arr[..].iter().cloned() {
        for i in 0..32 {
            if a%2 == 1 {
                v[i] += 1;
            }
            a /= 2;
        }
    }

    let mut best = 0;
    let mut best_index = 0;
    for (index, mut a) in arr[..].iter().cloned().enumerate() {
        let mut x = 0;
        for i in 0..32 {
            if a%2 == 1 && v[i] == 1 {
                x += 1 << i;
            }
            a /= 2;
        }
        if x > best {
            best = x;
            best_index = index;
        }
    }

    println!("{}", arr[best_index]);
    for (index, a) in arr[..].iter().enumerate() {
        if index != best_index {
            println!("{}", a);
        }
    }
}


use std::io::Write;

fn read_line() -> String {
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer).unwrap();
    buffer
}

fn main() {
    let _n = read_line().trim().parse::<u32>().unwrap();

    let line = read_line();
    let arr = line.split(" ").map(|x| x.trim().parse::<u32>().unwrap()).collect::<Vec<_>>();

    let mut v = vec![0; 32];

    for mut a in arr[..].iter().cloned() {
        for i in 0..32 {
            if a%2 == 1 {
                v[i] += 1;
            }
            a /= 2;
        }
    }

    let mut best = 0;
    let mut best_index = 0;
    for (index, mut a) in arr[..].iter().cloned().enumerate() {
        let mut x = 0;
        for i in 0..32 {
            if a%2 == 1 && v[i] == 1 {
                x += 1 << i;
            }
            a /= 2;
        }
        if x > best {
            best = x;
            best_index = index;
        }
    }

    let stdout = std::io::stdout();
    let mut writer = std::io::BufWriter::new(stdout.lock());

    write!(writer, "{}\n", arr[best_index]).unwrap();
    for (index, a) in arr[..].iter().enumerate() {
        if index != best_index {
            write!(writer, "{}\n", a).unwrap();
        }
    }

    writer.flush().unwrap();
}


//https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8 より
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

// ここまで

fn run() {
    input! {
        n: usize,
        a: [usize; n],
    }
    let m = 30;
    let mut val = vec![1_000_000_001; m];
    let mut cnt = vec![0; m];
    for &a in a.iter() {
        for i in 0..m {
            if (a >> i) & 1 == 1 {
                cnt[i] += 1;
                val[i] = a;
            }
        }
    }
    let mut ans = a.clone();
    for i in (0..m).rev() {
        if cnt[i] == 1 {
            ans.clear();
            let v = val[i];
            ans.push(v);
            let mut k = 0;
            while k < n && a[k] != v {
                ans.push(a[k]);
                k += 1;
            }
            k += 1;
            while k < n {
                ans.push(a[k]);
                k += 1;
            }
            break;
        }
    }
    let mut out = String::new();
    for a in ans {
        out.push_str(&format!("{} ", a));
    }
    out.pop();
    println!("{}", out);
}

fn main() {
    run();
}


macro_rules! parse_line {
    ($t: ty) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let a_str = a_str.trim();
        a_str.parse::<$t>().expect("parse error")
    });
    ($($t: ty),+) => ({
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        let mut a_iter = a_str.split_whitespace();
        (
            $(
            a_iter.next().unwrap().parse::<$t>().expect("parse error"),
            )+
        )
    })
}

#[allow(unused_macros)]
macro_rules! parse_line_to_vec {
    ($t: ty) => {{
        let mut a_str = String::new();
        std::io::stdin().read_line(&mut a_str).expect("read error");
        (a_str
            .split_whitespace()
            .map(|x| x.parse::<$t>().unwrap())
            .collect::<Vec<$t>>())
    }};
}

use std::io::Write;

fn solve(writer: &mut std::io::BufWriter<std::io::Stdout>) {
    let n = parse_line!(usize);
    let mut a = parse_line_to_vec!(u32);
    let mut counts = [0; 30];
    for &x in &a {
        for i in 0..30 {
            if (x >> i) & 1 != 0 {
                counts[i] += 1;
            }
        }
    }
    let mut mask = 0;
    for i in 0..30 {
        if counts[i] == 1 {
            mask |= 1 << i;
        }
    }
    let mut id = 0;
    for i in 1..n {
        if a[i] & mask >= a[id] & mask {
            id = i;
        }
    }
    let t = a[id];
    a[id] = a[0];
    a[0] = t;
    for x in a {
        write!(writer, "{} ", x).unwrap();
    }
    writeln!(writer).unwrap();
}

fn main() {
    let mut writer = std::io::BufWriter::new(std::io::stdout());
    let tests = 1; // parse_line!(usize);
    for _ in 0..tests {
        solve(&mut writer);
    }
}


#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

    ($next:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($next, $t);
        input_inner!{$next $($r)*}
    };
}

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, [ $t:tt ]) => {{
        let len = read_value!($next, usize);
        (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    }};

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

#[allow(unused)]
macro_rules! debug {
    ($($format:tt)*) => (write!(std::io::stderr(), $($format)*).unwrap());
}
#[allow(unused)]
macro_rules! debugln {
    ($($format:tt)*) => (writeln!(std::io::stderr(), $($format)*).unwrap());
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (let _ = write!(out,$($format)*););
    }
    input! {
        n: usize,
        a: [i32; n],
    }
    const B: i32 = 30;
    let mut top = -1;
    let mut head = 0;
    for i in (0..B).rev() {
        let mut cnt = vec![];
        for j in 0..n {
            if (a[j] & 1 << i) != 0 {
                cnt.push(j);
            }
        }
        if cnt.len() != 1 {
            continue;
        }
        top = i;
        head = cnt[0];
        break;
    }
    let mut a = a;
    if top >= 0 {
        a.swap(head, 0);
    }
    for i in 0..n {
        puts!("{}{}", a[i], if i + 1 == n { "\n" } else { " " });
    }
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}


package main

import (
	"fmt"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}

func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}

func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	a = make([]int, n, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &a[i])
		popcount(a[i])
	}
	fmt.Println(a)
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] ++
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		fmt.Printf("%d ", a[kt[i]])
	}
}


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}
func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}
func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func CF1299A(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n int
	Scanf("%d\n", &n)
	a = make([]int, n, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		Scanf("%d", &a[i])
		popcount(a[i])
	}
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] |= 1 << uint(j)
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		Fprintf(out, "%d ", a[kt[i]])
	}
}

func main() { CF1299A(os.Stdin, os.Stdout) }


package main

import (
	"fmt"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}

func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}

func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	a = make([]int, n, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &a[i])
		popcount(a[i])
	}
	fmt.Println(a)
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] ++
			}
		}
	}
	for i := 0; i < n; i++ {
		fmt.Printf("%d ", a[kt[i]])
	}
}


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}
func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}
func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func CF1299A(_r io.Reader, _w io.Writer) {
	in := bufio.NewReader(_r)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n int
	Fscan(in, &n)
	a = make([]int, n, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		Fscan(in, &a[i])
		popcount(a[i])
	}
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] |= 1 << uint(j)
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		Fprintf(out, "%d ", a[kt[i]])
	}
}

func main() { CF1299A(os.Stdin, os.Stdout) }


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}
func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}
func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func CF1299A(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n int
	Scanf("%d", &n)
	a = make([]int, n, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		Scanf("%d", &a[i])
		popcount(a[i])
	}
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] |= 1 << uint(j)
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		Fprintf(out, "%d ", a[kt[i]])
	}
}

func main() { CF1299A(os.Stdin, os.Stdout) }


package main

import (
	"fmt"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}

func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}

func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func main() {
	var n int
	fmt.Scanf("%d\n", &n)
	a = make([]int, n, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &a[i])
		popcount(a[i])
	}
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] ++
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		fmt.Printf("%d ", a[kt[i]])
	}
}


package main

import (
	"fmt"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}

func (p myInt) Less(i, j int) bool {
	return has[i] > has[j]
}

func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func main() {
	var (
		n, tmp int
	)
	fmt.Scanf("%d", &n)
	a = make([]int, 0, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &tmp)
		a = append(a, tmp)
		popcount(tmp)
	}
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] ++
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		fmt.Printf("%d ", a[kt[i]])
	}
}


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}
func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}
func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func CF1299A(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}
	n := read()
	a = make([]int, n, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		a[i] = read()
		popcount(a[i])
	}
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] |= 1 << uint(j)
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		Fprintf(out, "%d ", a[kt[i]])
	}
}

func main() { CF1299A(os.Stdin, os.Stdout) }


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}

func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}

func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func CF1299A(_r io.Reader, _w io.Writer) {
	in := bufio.NewScanner(_r)
	in.Split(bufio.ScanWords)
	out := bufio.NewWriter(_w)
	defer out.Flush()
	read := func() (x int) {
		in.Scan()
		for _, b := range in.Bytes() {
			x = x*10 + int(b-'0')
		}
		return
	}
	n := read()
	a = make([]int, n, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		a[i] = read()
		popcount(a[i])
	}
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] ++
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		Fprintf(out, "%d ", a[kt[i]])
	}
}

func main() { CF1299A(os.Stdin, os.Stdout) }


package main

import (
	"bufio"
	. "fmt"
	"io"
	"os"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}
func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}
func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func CF1299A(_r io.Reader, _w io.Writer) {
	out := bufio.NewWriter(_w)
	defer out.Flush()
	var n int
	Fscan(_r, &n)
	a = make([]int, n, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		Fscan(_r, &a[i])
		popcount(a[i])
	}
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] |= 1 << uint(j)
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		Fprintf(out, "%d ", a[kt[i]])
	}
}

func main() { CF1299A(os.Stdin, os.Stdout) }


package main

import (
	"fmt"
	"sort"
)

type myInt []int
var c [32]int
var has, a []int
var kt myInt

func popcount(x int) {
	for i := 0; i < 32; i++ {
		if 1 == (1 & (x >> uint(i))) {
			c[i] ++
		}
	}
}

func (p myInt) Len() int {
	return len(p)
}

func (p myInt) Less(i, j int) bool {
	return has[p[i]] > has[p[j]]
}

func (p myInt) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func main() {
	var (
		n, tmp int
	)
	fmt.Scanf("%d", &n)
	a = make([]int, 0, n)
	has = make([]int, n, n)
	kt = make(myInt, n, n)
	for i := 0; i < n; i++ {
		fmt.Scanf("%d", &tmp)
		a = append(a, tmp)
		popcount(tmp)
	}
	for i := 0; i < n; i++ {
		kt[i] = i
		for j := 0; j < 32; j++ {
			if c[j] == 1 && ((a[i] >> uint(j) & 1) == 1) {
				has[i] ++
			}
		}
	}
	sort.Sort(kt)
	for i := 0; i < n; i++ {
		fmt.Printf("%d ", a[kt[i]])
	}
}


// Author: sighduck
// URL: https://codeforces.com/contest/1299/problem/A

package main

import (
	"bufio"
	"fmt"
	"os"
)

func Solve(n int, a []int64) []int64 {
	prefix := make([]int64, n)
	suffix := make([]int64, n)
	prefix[0] = ^a[0]
	for i := 1; i < n; i++ {
		prefix[i] = ^a[i] & prefix[i-1]
	}
	suffix[n-1] = ^a[n-1]
	for i := n - 2; i >= 0; i-- {
		suffix[i] = ^a[i] & suffix[i+1]
	}
	max := int64(0)
	maxI := 0
	for i := 0; i < n; i++ {
		val := a[i]
		if i-1 >= 0 {
			val &= prefix[i-1]
		}
		if i+1 <= n-1 {
			val &= suffix[i+1]
		}
		if val > max {
			max = val
			maxI = i
		}
	}
	a[0], a[maxI] = a[maxI], a[0]
	return a
}

func main() {
	reader := bufio.NewReader(os.Stdin)
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	var n int
	fmt.Fscanf(reader, "%d\n", &n)
	a := make([]int64, n)
	for i := 0; i < n; i++ {
		fmt.Fscanf(reader, "%d", &a[i])
	}
	fmt.Fscanf(reader, "\n")

	for _, elem := range Solve(n, a) {
		fmt.Fprintf(writer, "%d ", elem)
	}
	fmt.Fprintf(writer, "\n")
}


<?php

namespace io {
	$input_file_content = file_get_contents("php://stdin");
	$input_buf = explode("\n", $input_file_content);
	unset($input_file_content);
}

namespace main {
	error_reporting(E_ALL);
	ini_set('display_errors', true);
	ini_set('html_errors', false);

	use function io\next_line as next_line;
	use function io\next_ as next;
	use function io\next_int as next_int;
	use function io\next_double as next_double;

	$n = next_int();
	for($i=0; $i<$n; $i++) {
		$a[] = next_int();
	}

	$front[] = $a[0];
	$back[$n-1] = $a[$n-1];
	for($i=1; $i<$n; $i++) {
		$front[] = $front[$i-1] | $a[$i];
		$back[$n-$i-1] = $back[$n-$i] | $a[$n-$i-1];
	}

	$ans = -1;
	$idx = -1;
	for($i=0; $i<$n; $i++) {
		$l = ($i > 0) ? $front[$i-1] : 0;
		$r = ($i < $n-1) ? $back[$i+1] : 0;
		$y = ($l | $r);
		$temp = ($a[$i] | $y) - $y;
		if($temp > $ans) {
			$ans = $temp;
			$idx = $i;
		}
	}

	$first = $a[$idx];
	unset($a[$idx]);

	printf("%d %s\n", $first, implode(" ", $a));
}

namespace io {
	function next_line() {
		static $cnt = 0;
		global $input_buf;
		// while($input_buf[$cnt] == "") $cnt++;
		return $input_buf[$cnt++];
		// return trim($input_buf[$cnt++]);
	}
	function next_() {
		static $tk = [];
		static $tk_cnt = 0;
		if($tk_cnt == count($tk)) {
			$tk = explode(" ", next_line());
			$tk_cnt = 0;
		}
		return $tk[$tk_cnt++];
	}
	function next_int() {
		return (int)next_();
	}
	function next_double() {
		return (double)next_();
	}
}

?>


from __future__ import division,print_function
#from sortedcontainers import SortedList
import sys
#sys.__stdout__.flush()
le=sys.__stdin__.read().split("\n")
le.pop()
le=le[::-1]
n=int(le.pop())
l=list(map(bin,map(int,le.pop().split())))
d=max(map(len,l))
l=['0'*(d-len(k))+k[2:] for k in l]
d-=2
#print(l)
tab=[0]*d
for k in l:
    for i in range(d):
        tab[i]+=int(k[i])
m='0'*d
im=0
for k in range(n):
    v=l[k]
    te=''.join(str(i if j==1 else 0) for i,j in zip(v,tab))
    if te>m:
        m=te
        im=k
m=l[im]
l.remove(m)
l=[m]+l
l=[str(sum(2**(d-1-i)*int(k[i]) for i in range(d))) for k in l]
#print(l)
print(" ".join(l))


from __future__ import division,print_function
#from sortedcontainers import SortedList
import sys
#sys.__stdout__.flush()
le=sys.__stdin__.read().split("\n")
le.pop()
le=le[::-1]
n=int(le.pop())
l=list(map(bin,map(int,le.pop().split())))
d=max(map(len,l))
l=['0'*(d-len(k))+k[2:] for k in l]
d-=2
#print(l)
tab=[0]*d
for k in l:
    for i in range(d):
        tab[i]+=int(k[i])
m='0'*d
im=0
for k in range(n):
    v=l[k]
    te=''.join(str(i if j==1 else 0) for i,j in zip(v,tab))
    if te>m:
        m=te
        im=k
m=l[im]
l.remove(m)
l=[m]+l
l=[str(sum(2**(d-1-i)*int(k[i]) for i in range(d))) for k in l]
print(l)
print(" ".join(l))


from __future__ import print_function # for PyPy2
from collections import Counter, OrderedDict
from itertools import permutations as perm
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math

g   = lambda : stdin.readline().strip()
gl  = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")

n, = gil()
a = gil()
pre, suf = [~a[0]], [~a[-1]]

for i in xrange(1, n):
	pre.append(pre[-1]&(~a[i]))

for i in reversed(xrange(n-1)):
	suf.append((~a[i])&suf[-1])
suf.reverse()

idx = 0

def getVal(x):
	v = a[x]
	if x :
		v &= pre[x-1]
	if x+1 < n:
		v &= suf[x+1]
	return v

for i in range(n):
	idx = max(idx, i, key=getVal)

a = [a.pop(idx)] + a

print(*a)


from __future__ import print_function # for PyPy2
from collections import Counter, OrderedDict
from itertools import permutations as perm
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math

g   = lambda : stdin.readline().strip()
gl  = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")

n, = gil()
a = gil()
pre, suf = [~a[0]], [~a[-1]]

for i in xrange(1, n):
	pre.append(pre[-1]&(~a[i]))

for i in reversed(xrange(n-1)):
	suf.append((~a[i])&suf[-1])
suf.reverse()

idx = 0

def getVal(x):
	v = a[x]
	if x :
		v &= pre[x-1]
	if x+1 < n:
		v &= suf[x+1]
	return v

for i in range(n):
	idx = max(idx, i, key=getVal)

a = [a[idx]] + a[:idx] + a[idx+1:]

print(*a)


from __future__ import print_function # for PyPy2
from collections import Counter, OrderedDict
from itertools import permutations as perm
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math

g   = lambda : stdin.readline().strip()
gl  = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")

n, = gil()
a = gil()
pre, suf = [~a[0]], [~a[-1]]

for i in xrange(1, n):
	pre.append(pre[-1]&(~a[i]))

for i in reversed(xrange(n-1)):
	suf.append((~a[i])&suf[-1])
suf.reverse()

idx = 0

def getVal(x):
	v = a[x]
	if x :
		v &= pre[x-1]
	if x+1 < n:
		v &= suf[x+1]
	return v

for i in xrange(n):
	idx = max(idx, i, key=getVal)

print(a[idx], end=" ")
for i in xrange(n):
	if i!= idx:
		print(a[i], end=" ")

print()


from __future__ import print_function # for PyPy2
from collections import Counter, OrderedDict
from itertools import permutations as perm
from collections import deque
from sys import stdin
from bisect import *
from heapq import *
import math

g   = lambda : stdin.readline().strip()
gl  = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")

n, = gil()
a = gil()
pre, suf = [~a[0]], [~a[-1]]

for i in xrange(1, n):
	pre.append(pre[-1]&(~a[i]))

for i in reversed(xrange(n-1)):
	suf.append((~a[i])&suf[-1])
suf.reverse()

idx = 0

def getVal(x):
	v = a[x]
	if x :
		v &= pre[x-1]
	if x+1 < n:
		v &= suf[x+1]
	return v

for i in xrange(n):
	idx = max(idx, i, key=getVal)

ans = []
ans.append(str(a[idx]))
for i in xrange(n):
	if i!= idx:
		ans.append(str(a[i]))

print(" ".join(ans))


import sys
range = xrange
input = raw_input

n = int(input())
A = [int(x) for x in input().split()]

bit = 2**30
while bit:
    B = []
    for i in range(n):
        if A[i] & bit:
            B.append(i)

    if len(B) == 1:
        print ' '.join(str(x) for x in [A[B[0]]] + A[:B[0]] + A[B[0] + 1:])
        sys.exit()
    bit >>= 1
print ' '.join(str(x) for x in A)


from sys import stdin, stdout

def main():
    n = int(stdin.readline())
    arr = list(map(int, stdin.readline().split()))
    pow2 = [0] * 32
    max = 0
    ans = [0] * 32
    for j,i in enumerate(arr):
        x = int(i)
        z = 0
        while x > 0:
            if (x - pow(2,z)) % pow(2,z+1) == 0:
                x -= pow(2,z)
                pow2[z]+= 1
                if pow2[z] == 1:
                    ans[z] = j
            z += 1
    for i,x in enumerate(pow2):
        if x == 1:
            max = i

    if pow2[max] == 1:
        arr[0], arr[ans[max]] = arr[ans[max]], arr[0]

    stdout.write(" ".join(str(x) for x in arr))


from sys import stdin, stdout

def main():
    n = int(stdin.readline())
    arr = list(map(int, stdin.readline().split()))
    pow2 = [0] * 32
    max = 0
    ans = [0] * 32
    for j,i in enumerate(arr):
        x = int(i)
        z = 0
        while x > 0:
            if (x - pow(2,z)) % pow(2,z+1) == 0:
                x -= pow(2,z)
                pow2[z]+= 1
                if pow2[z] == 1:
                    ans[z] = j
            z += 1
    for i,x in enumerate(pow2):
        if x == 1:
            max = i

    if pow2[max] == 1:
        arr[0], arr[ans[max]] = arr[ans[max]], arr[0]

    stdout.write(" ".join(str(x) for x in arr))

main()


n = int(input())
arr = [int(p) for p in input().split()]
print(*sorted(arr, reverse=True))


n = int(input())
arr = [int(p) for p in input().split()]
pre = [~arr[0]]
suff = [~arr[-1]]
for i in range(1, n):
    pre.append(pre[-1]&(~arr[i]))
for i in range(n-2, -1, -1):
    suff.append(suff[-1]&(~arr[i]))
curr = 0
if n == 1:
    print(*arr)
    exit(0)
suff = list(reversed(suff))
l = arr[0]&suff[1]
r = arr[-1]&pre[n-2]
curr = max(l, r)
if curr == l:
    piv = l
else:
    piv = r
for i in range(1, n-1):
    prev = curr
    curr = max(curr, pre[i-1]&arr[i]&suff[i+1])
    if prev != curr:
        piv = arr[i]
ans = [piv]
for i in arr:
    if i != piv:
        ans.append(i)
print(*ans)


n = int(input())
arr = [int(p) for p in input().split()]
print(sorted(arr, reverse=True))


n = int(input())
arr = [int(p) for p in input().split()]
pre = [~arr[0]]
suff = [~arr[-1]]
for i in range(1, n):
    pre.append(pre[-1]&(~arr[i]))
for i in range(n-2, -1, -1):
    suff.append(suff[-1]&(~arr[i]))
curr = 0
if n == 1:
    print(*arr)
    exit(0)
suff = list(reversed(suff))
l = arr[0]&suff[1]
r = arr[-1]&pre[n-2]
curr = max(l, r)
if curr == l:
    piv = arr[0]
else:
    piv = arr[-1]
for i in range(1, n-1):
    prev = curr
    curr = max(curr, pre[i-1]&arr[i]&suff[i+1])
    if prev != curr:
        piv = arr[i]
ans = [piv]
for i in arr:
    if i != piv:
        ans.append(i)
print(*ans)


n = int(input())
arr = [int(p) for p in input().split()]
pre = [~arr[0]]
suff = [~arr[-1]]
for i in range(1, n):
    pre.append(pre[-1]&(~arr[i]))
for i in range(n-2, -1, -1):
    suff.append(suff[-1]&(~arr[i]))
curr = 0
if n == 1:
    print(*arr)
    exit(0)
suff = list(reversed(suff))
l = arr[0]&suff[1]
r = arr[-1]&pre[n-2]
curr = max(l, r)
if curr == l:
    piv = arr[0]
else:
    piv = arr[-1]
for i in range(1, n-1):
    prev = curr
    curr = max(curr, pre[i-1]&arr[i]&suff[i+1])
    if prev != curr:
        piv = arr[i]
ans = [piv]
arr.remove(piv)
arr.insert(0, piv)
print(*arr)


n = int(input())
arr = [int(p) for p in input().split()]
pre = [~arr[0]]
suff = [~arr[-1]]
for i in range(1, n):
    pre.append(pre[-1]&(~arr[i]))
for i in range(n-2, -1, -1):
    suff.append(suff[-1]&(~arr[i]))
curr = 0
if n == 1:
    print(*arr)
    exit(0)
l = arr[0]&suff[n-2]
r = arr[-1]&pre[n-2]
curr = max(l, r)
if curr == l:
    piv = l
else:
    piv = r
for i in range(1, n-1):
    prev = curr
    curr = max(curr, pre[i-1]&arr[i]&suff[n-i-2])
    if prev != curr:
        piv = arr[i]
ans = [piv]
for i in arr:
    if i != piv:
        ans.append(i)
print(*ans)


n = int(input())
arr = [int(p) for p in input().split()]
pre = [~arr[0]]
suff = [~arr[-1]]
for i in range(1, n):
    pre.append(pre[-1]&(~arr[i]))
for i in range(n-2, -1, -1):
    suff.append(suff[-1]&(~arr[i]))
curr = 0
if n == 1:
    print(*arr)
    exit(0)
suff = list(reversed(suff))
l = arr[0]&suff[1]
r = arr[-1]&pre[n-2]
curr = max(l, r)
if curr == l:
    piv = arr[0]
else:
    piv = arr[-1]
print(piv)
for i in range(1, n-1):
    print('ll')
    prev = curr
    curr = max(curr, pre[i-1]&arr[i]&suff[i+1])
    if prev != curr:
        piv = arr[i]
ans = [piv]
for i in arr:
    if i != piv:
        ans.append(i)
print(*ans)


def answer(n,arr):
    arr.sort(reverse=True)
    return arr

n=int(input())
arr=list(map(int,input().split()))
print(*answer(n,arr))


def answer(n,A):
    if n==1:
        return A

    pre=[0]*n
    pre[0]=(~A[0])
    for i in range(1,n):
        pre[i]=(~A[i]&pre[i-1])
    suff=[0]*n
    suff[-1]=~A[-1]
    for i in range(n-2,-1,-1):
        suff[i]=(~A[i]&suff[i+1])

    ele=A[0]
    maxi=A[0]&suff[1]
    ans=0
    for i in range(1,n):
        if i==n-1:
            ans=A[i]&pre[i-1]
        else:
            ans=A[i]&(pre[i-1]&suff[i+1])

        if ans>maxi:
            maxi=ans
            ele=A[i]

    A.remove(ele)
    return [ele]+A

n=int(input())
arr=list(map(int,input().split()))
print(*answer(n,arr))


def answer(n,arr):
    arr.sort()
    return arr

n=int(input())
arr=list(map(int,input().split()))
print(*answer(n,arr))


import math
import collections
import sys

def inpu():
    return input().split(' ')

def inti(a):
    for i in range(len(a)):
        a[i] = int(a[i])
    return a

def inp():
    a = inpu()
    a = inti(a)
    return a

def solution():
    N = inp()
    A = inp()

    ans = -1
    for i in range(32, -1, -1):
        count = 0
        for n in A:
            if (((1 << i) & n) != 0):
                ans = n
                count += 1
        if count == 1:
            break
        ans = -1

    if ans != -1:
        print(ans, end=' ')

    for n in A:
        if n != ans:
            print(n, end=' ')

solution()


n = int(input())

a = [int(x) for x in input().split()]

# mask = 2**30
# while mask and len([ai for ai in a if ai & mask])!=1:
#     mask>>=1
#
# if mask:
#     print (next(i for i in range(n) if a[i] & mask))
#     i = next((i for i in range(n) if a[i] & mask))
#     print ((i for i in range(n) if a[i] & mask))
#     a[i], a[0] = a[0], a[i]
# print (*a)

a.sort(reverse=True)

mask = 2**30
while mask and len([ai for ai in a if ai & mask])!=1:
    mask>>=1
for i in range(n):
    if mask&a[i]:
        break
a[i], a[0] = a[0], a[i]
print (*a)


#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction

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")

#-------------------game starts now----------------------------------------------------
n=int(input())
a=list(map(int,input().split()))
pre=[0]*n
suf=[0]*n
el=~a[0]
for i in range (1,n):
    pre[i]=el&(~a[i-1])
    el=el&(~a[i-1])
#print(pre)
el=~a[-1]
for i in range (n-2,-1,-1):
    suf[i]=el&(~a[i+1])
    el=el&(~a[i+1])
#print(suf)
pre[0]=suf[0]
suf[-1]=pre[-1]
mx=0
ind=-1
for i in range (n):
    curr=a[i]&pre[i]&suf[i]
    #print(curr)
    if curr>mx:
        mx=curr
        ind=i
t=a[ind]
a[ind]=a[0]
a[0]=t
print(*a)


from operator import or_
from itertools import accumulate
_ = input()
l = list(map(int, input().strip().split()))
lx = accumulate(l, or_, initial=0)
rx = reversed(list(accumulate(reversed(l), or_, initial=0)))
next(rx)
print(max(i & ~(a | b) for i, a, b in zip(l, lx, rx)))


from operator import or_
from itertools import accumulate
_ = input()
l = [*map(int, input().strip().split())]
lx = [0, *accumulate(l, or_)]
rx = [*reversed(list(accumulate(reversed(l), or_)))]
rx.append(0)
print(max(i & ~(a | b) for i, a, b in zip(l, lx, rx[1:])))


from operator import or_
from itertools import accumulate
_ = input()
l = [*map(int, input().strip().split())]
lx = [0, *accumulate(l, or_)]
rx = [*reversed(list(accumulate(reversed(l), or_))), 0]
_, idx = max((x & ~(a | b), i) for i, (x, a, b) in enumerate(zip(l, lx, rx[1:])))
print(*l[idx - len(l): idx])


from operator import or_
from itertools import accumulate
_ = input()
l = [*map(int, input().strip().split())]
lx = [0, *accumulate(l, or_)]
rx = [*reversed(list(accumulate(reversed(l), or_))), 0]
_, idx = max((x & ~(a | b), i) for i, (x, a, b) in enumerate(zip(l, lx, rx[1:])))
print(*l[idx:], *l[:idx])


from operator import or_
from itertools import accumulate
_ = input()
l = list(map(int, input().strip().split()))
lx = accumulate(l, or_, initial=0)
rx = reversed(list(accumulate(reversed(l), or_, initial=0)))
next(rx)
_, idx = max((x & ~(a | b), i) for i, (x, a, b) in enumerate(zip(l, lx, rx)))
print(*(l[idx:]+*l[:idx]))


from operator import or_
from itertools import accumulate
_ = input()
l = list(map(int, input().strip().split()))
lx = accumulate(l, or_, initial=0)
rx = reversed(list(accumulate(reversed(l), or_, initial=0)))
next(rx)
_, idx = max((x & ~(a | b), i) for i, (x, a, b) in enumerate(zip(l, lx, rx)))
print(*(l[idx:] + l[:idx]))


from operator import or_
from itertools import accumulate
_ = input()
l = list(map(int, input().strip().split()))
lx = accumulate(l, or_, initial=0)
rx = reversed(list(accumulate(reversed(l), or_, initial=0)))
next(rx)
_, idx = max((x & ~(a | b), i) for i, (x, a, b) in enumerate(zip(l, lx, rx)))
print(*l[idx:], *l[:idx])


n = int(input())
lst = list(map(int,input().split()))
lst.sort()

print(*lst)


n   = int(input())
lst = list(map(int,input().split()))

pre = [0 for i in range(n+1)]
suf = [0 for i in range(n+1)]

pre[1] = ~lst[0]
for i in range(1,n):
	pre[i+1] = pre[i]&(~lst[i])

suf[n-1] = ~lst[n-1]
for i in range(n-2,-1,-1):
	suf[i] = suf[i+1]&(~lst[i])

Max = -float('inf')
Ans = None

for i in range(n):
	temp = pre[i]&lst[i]&suf[i+1]
	if(temp>Max):
		Ans = i
		Max = temp

print(lst[Ans],end=' ')
for i in range(n):
	if(i==Ans):
		continue
	else:
		print(lst[i],end=' ')
print()


import sys
n   = int(input())
lst = list(map(int,input().split()))

pre = [0 for i in range(n+1)]
suf = [0 for i in range(n+1)]

pre[0] = sys.maxsize

for i in range(n):
	pre[i+1] = pre[i]&(~lst[i])

suf[n] = sys.maxsize
for i in range(n-1,-1,-1):
	suf[i] = suf[i+1]&(~lst[i])

Max = -sys.maxsize
Ans = None

for i in range(n):
	temp = pre[i]&lst[i]&suf[i+1]
	if(temp>Max):
		Ans = i
		Max = temp

print(lst[Ans],end=' ')
for i in range(n):
	if(i==Ans):
		continue
	else:
		print(lst[i],end=' ')
print()


n = int(input())
lst = list(map(int,input().split()))
lst.sort(reverse=True)

print(*lst)


n = int(input())
a = list(map(int, input().split()))

ans = 0
f = [0 for i in range(n)]
b = [0 for i in range(n)]

for i in range(n):
    f[i] = a[i] | (f[i - 1] if i - 1 >= 0 else 0)

for i in range(n - 1, -1, -1):
    b[i] = a[i] | (b[i + 1] if i + 1 < n else 0)
index = 0
for i in range(n):
    left = (f[i - 1] if i - 1 >= 0 else 0) | ((b[i + 1] if i + 1 < n else 0))
    temp = a[i] - (a[i] & left)
    # print(left)
    # print(a[i], temp)
    ans = max(temp, ans)
    if temp == ans:
        index = i
print(a[index], end=' ')
for i in range(n):
    if i != index:
        print(a[i], end=' ')
print('')


n = int(input())
a = list(map(int, input().split()))
r = 0

for i in range(29, -1, -1):
    c = 0
    for j in a:
        if (j >> i) & 1:
            c += 1
            r = j
    if c == 1:
        break

a.remove(r)

print(r, ' '.join(map(str, a)))


"""
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk

"""
# import sys
# input = sys.stdin.buffer.readline

def solution():
    n=int(input())
    l=list(map(int,input().split()))
    nl=[]
    pre=[~l[0]]
    suff=[]
    for i in range(n):
        x=~l[i]
        # print(x)
        nl.append(x)
        pre.append(x)
        suff.append(x)
    suff.append(~l[-1])
    # print(suff)
    for i in range(1,n+1):
        pre[i]&=pre[i-1]
    for i in range(n-1,-1,-1):
        suff[i]&=suff[i+1]
    # print(suff)
    m=-1
    for i in range(n):
        # print(pre[i],suff[i+1])
        x=l[i]&pre[i]&suff[i+1]
        # print(l[i],x)
        if x>m:
            m=x
            j=i
    l[0],l[j]=l[j],l[0]
    print(*l)
solution()
# print(124252105&~315479581&~954336048 &~880492165 &~179952043)


"""
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk

"""
# import sys
# input = sys.stdin.buffer.readline

def solution():
    n=int(input())
    l=list(map(int,input().split()))
    nl=[]
    pre=[1]
    suff=[]
    for i in range(n):
        x=~l[i]
        nl.append(x)
        pre.append(x)
        suff.append(x)
    suff.append(1)
    for i in range(1,n):
        pre[i]&=pre[i-1]
    for i in range(n-1,-1,-1):
        suff[i]&=suff[i+1]
    m=-1
    for i in range(n):
        x=pre[i]&suff[i+1]
        if x>m:
            m=x
            j=i
    l[0],l[j]=l[j],l[0]
    print(*l)
solution()


"""
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk

"""
# import sys
# input = sys.stdin.buffer.readline

def solution():
    n=int(input())
    l=list(map(int,input().split()))
    nl=[]
    pre=[1]
    suff=[]
    for i in range(n):
        x=~l[i]
        nl.append(x)
        pre.append(x)
        suff.append(x)
    suff.append(1)
    for i in range(1,n+1):
        pre[i]&=pre[i-1]
    for i in range(n-1,-1,-1):
        suff[i]&=suff[i+1]
    m=-1
    for i in range(n):
        x=l[i]&pre[i]&suff[i+1]
        if x>=m:
            m=x
            j=i
    l[0],l[j]=l[j],l[0]
    print(*l)
solution()


"""
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk

"""
# import sys
# input = sys.stdin.buffer.readline

def solution():
    n=int(input())
    l=list(map(int,input().split()))
    nl=[]
    pre=[~l[0]]
    suff=[]
    for i in range(n):
        x=~l[i]
        # print(x)
        nl.append(x)
        pre.append(x)
        suff.append(x)
    suff.append(~l[-1])
    for i in range(1,n+1):
        pre[i]&=pre[i-1]
    for i in range(n-1,-1,-1):
        suff[i]&=suff[i+1]
    # print(suff)
    # print(pre)
    m=-1
    for i in range(n):
        if i==0:
            x=l[i]&suff[i+1]
        elif i==n-1:
            x=l[i]&pre[i]
        else:
            x=l[i]&suff[i+1]&pre[i]
        if x>m:
            m=x
            j=i
    l[0],l[j]=l[j],l[0]
    print(*l)
solution()
# print(0&~179952043)


"""
Code of Ayush Tiwari
Codechef: ayush572000
Codeforces: servermonk

"""
# import sys
# input = sys.stdin.buffer.readline

def solution():
    n=int(input())
    l=list(map(int,input().split()))
    nl=[]
    pre=[~l[0]]
    suff=[]
    for i in range(n):
        x=~l[i]
        # print(x)
        nl.append(x)
        pre.append(x)
        suff.append(x)
    suff.append(~l[-1])
    for i in range(1,n+1):
        pre[i]&=pre[i-1]
    for i in range(n-1,-1,-1):
        suff[i]&=suff[i+1]
    # print(suff)
    # print(pre)
    m=-1
    for i in range(n):
        if i==0:
            x=l[i]&suff[i+1]
        elif i==n-1:
            x=l[i]&pre[i]
        else:
            x=l[i]&suff[i+1]
        if x>m:
            m=x
            j=i
    l[0],l[j]=l[j],l[0]
    print(*l)
solution()
# print(0&~179952043)


import sys
input = sys.stdin.readline

n=int(input())
A=list(map(int,input().split()))

count=[0]*32

for a in A:
    for i in range(32):
        if a & (1<<i) !=0:
            count[i]+=1

#print(count)

init=0
flag=0
for i in range(31,-1,-1):
    if count[i]==1:
        for j in range(n):
            if A[j] & (1<<i) !=0:
                init=j
                flag=1
                break

    if flag==1:
        break

ANS=[A[init]]

for i in range(n):
    if i==init:
        continue
    ANS.append(A[i])

print(*ANS)


import sys
input = sys.stdin.readline

n=int(input())
A=list(map(int,input().split()))
A.sort(reverse=True)
print(*A)


N = int(input())
A = list(map(int, input().split()))

ans = -1
for i in range(32, 0, -1):
    count = 0
    ans   = -1
    for n in A:
        if (((1 << i) & n) != 0):
            ans = n
            count += 1
    if count == 1:
        break

if ans != -1:
    print(ans, end = ' ')
    ans = -1

for n in A:
    if n != ans:
        print(n, end = ' ')


N = int(input())
A = list(map(int, input().split()))

ans = -1
for i in range(32, -1, -1):
    count = 0
    for n in A:
        if (((1 << i) & n) != 0):
            ans = n
            count += 1
    if count == 1:
        break
    ans   = -1

if ans != -1:
    print(ans, end = ' ')

for n in A:
    if n != ans:
        print(n, end = ' ')


N = int(input())
A = list(map(int, input().split()))

ans = -1
for i in range(32, 0, -1):
    count = 0
    ans   = -1
    for n in A:
        if (((1 << i) & n) != 0):
            ans = n
            count += 1
    if count == 1:
        break

if ans != -1:
    print(ans, end = ' ')

for n in A:
    if n != ans:
        print(n, end = ' ')
    else:
        ans = -1


N = int(input())
A = list(map(int, input().split()))

ans = -1
for i in range(32, 0, -1):
    count = 0
    ans   = -1
    for n in A:
        if (((1 << i) & n) != 0):
            ans = n
            count += 1
    if count == 1:
        break

if ans != -1:
    print(ans, end = ' ')
for n in A:
    if n != ans:
        print(n, end = ' ')


N = int(input())
A = list(map(int, input().split()))

ans = -1
for i in range(32, -1, -1):
    count = 0
    ans   = -1
    for n in A:
        if (((1 << i) & n) != 0):
            ans = n
            count += 1
    if count == 1:
        break

if ans != -1:
    print(ans, end = ' ')

for n in A:
    if n != ans:
        print(n, end = ' ')
    else:
        ans = -1


import time
startTimeProblem=time.time()

import fileinput, sys, itertools, functools
from math import *
from bisect import *
from heapq import *
from collections import *

def lcm(a, b):
    return (a*b)/gcd(a, b)

class InputHelper:
    def __init__(self):
        self.myinput = fileinput.input()

    def isLocal(self):
        return not fileinput.isstdin()

    def int(self):
        return int(self.myinput.readline().rstrip())

    def ints(self):
        return [int(_) for _ in self.myinput.readline().rstrip().split()]

    def str(self):
        return self.myinput.readline().rstrip()

    def strs(self):
        return [_ for _ in self.myinput.readline().rstrip().split()]

class OutputHelper:
    def int(self, a):
        print(a)

    def ints(self, a):
        print(" ".join([str(_) for _ in a]))

    def intsNL(self, a):
        for _ in a:
            print(_)

    def str(self, s):
        print(s)

    def strs(self, s):
        print(" ".join([_ for _ in s]))

    def strsNL(self, s):
        for st in s:
            print(st)

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
        self.prev = None

In = InputHelper()
Out = OutputHelper()

######################################

n = In.int()
a = In.ints()

# print("----")

# my = functools.reduce(lambda x,y:(x|y) -y, [179952043, 315479581, 954336048, 124252105, 880492165])
# theirs = functools.reduce(lambda x,y:(x|y) -y, [124252105, 179952043, 315479581, 880492165, 954336048])

# print(my)
# print(theirs)

# print("----")

# sys.exit()

bitsThere = [0]*32

for el in a:
    for i in range(32):
        bitsThere[i] += (el&(1<<i))>0

maxVal = 0
maxIdx = 0

for i,el in enumerate(a):
    for j in range(32):
        bitOn = ((1<<j)&el)>0

        if bitOn and bitsThere[j]>1:
            el ^= (1<<j)

    if el>maxVal:
        maxVal=el
        maxIdx=i

firstEl = a[maxIdx]
a.pop(maxIdx)
Out.ints([firstEl] + a)

######################################

if len(sys.argv)>2 and sys.argv[2]=="TIMEIT":
    fin = (time.time()-startTimeProblem)*1000
    print("{:.2f}".format(fin) + "ms")


import time
startTimeProblem=time.time()

import fileinput, sys, itertools, functools
from math import *
from bisect import *
from heapq import *
from collections import *

def lcm(a, b):
    return (a*b)/gcd(a, b)

class InputHelper:
    def __init__(self):
        self.myinput = fileinput.input()

    def isLocal(self):
        return not fileinput.isstdin()

    def int(self):
        return int(self.myinput.readline().rstrip())

    def ints(self):
        return [int(_) for _ in self.myinput.readline().rstrip().split()]

    def str(self):
        return self.myinput.readline().rstrip()

    def strs(self):
        return [_ for _ in self.myinput.readline().rstrip().split()]

class OutputHelper:
    def int(self, a):
        print(a)

    def ints(self, a):
        print(" ".join([str(_) for _ in a]))

    def intsNL(self, a):
        for _ in a:
            print(_)

    def str(self, s):
        print(s)

    def strs(self, s):
        print(" ".join([_ for _ in s]))

    def strsNL(self, s):
        for st in s:
            print(st)

class ListNode:
    def __init__(self, val):
        self.val = val
        self.next = None
        self.prev = None

In = InputHelper()
Out = OutputHelper()

######################################

n = In.int()
a = In.ints()

a.sort(reverse=True)

Out.ints(a)

######################################

if len(sys.argv)>2 and sys.argv[2]=="TIMEIT":
    fin = (time.time()-startTimeProblem)*1000
    print("{:.2f}".format(fin) + "ms")


import sys
readline = sys.stdin.readline

N = int(readline())
A = list(map(int, readline().split()))

M = (1<<32)-1
nA = [M^a for a in A]

ar = [M] + nA[:] + [M]
al = ar[:]

for i in range(1, N+2):
    al[i] &= al[i-1]
for i in range(N, -1, -1):
    ar[i] &= ar[i+1]

d = -1
ans = None
for i in range(N):
    a = A[i]
    res = a&al[i]&ar[i+2]
    if res > d:
        d = res
        ans = i

Ans = A[:]
Ans.remove(A[ans])
print(*([A[ans]] + Ans))


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=998244353
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

n=Int()
a=array()

pre=[~a[0]]
for i in range(1,n):
    pre.append( pre[-1] & (~a[i]))

a=a[::-1]
suf=[~a[0]]
for i in range(1,n):
    suf.append( suf[-1] & (~a[i]))

suf=suf[::-1]
a=a[::-1]

# print()
print(pre)
print(suf)
# print()

ma=-inf
key=0
here=0
for i in range(n):

    try:
        if(i!=0 and i!=n-1): here= suf[i+1] & pre[i-1] & (a[i])
        elif(i==0): here=suf[i+1]&a[i]
        else: here=pre[i-1]&a[i]
    except:
        pass

    if(here>ma):
        ma=here
        key=i

print(a[key],*[a[i] for i in range(n) if i!=key])


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=998244353
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

n=Int()
a=array()

pre=[~a[0]]
for i in range(1,n):
    pre.append( pre[-1] & (~a[i]))

a=a[::-1]
suf=[~a[0]]
for i in range(1,n):
    suf.append( suf[-1] & (~a[i]))

suf=suf[::-1]
a=a[::-1]

# # print()
# print(pre)
# print(suf)
# # print()

ma=-inf
key=0
here=0
for i in range(n):

    try:
        if(i!=0 and i!=n-1): here= suf[i+1] & pre[i-1] & (a[i])
        elif(i==0): here=suf[i+1]&a[i]
        else: here=pre[i-1]&a[i]
    except:
        pass

    if(here>ma):
        ma=here
        key=i

print(a[key],*[a[i] for i in range(n) if i!=key])


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
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")
ALPHA='abcdefghijklmnopqrstuvwxyz'
M=998244353
EPS=1e-6
def value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]

#-------------------------code---------------------------#
# vsInput()

def invert(n):
    if(n==0): return inf
    x=int(log2(n))
    m=1<<x
    m=m|m-1
    n=n^m
    return n

def bits(n):
    c=0
    # print(n)
    while(n>0):
        c+=1
        n=n>>1
    # print(n,c)
    return c

n=Int()
a=array()

a.sort(key= lambda x:[-bits(x),invert(x)])
print(*a)