Maximum XOR of Two Numbers in an Array

 Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.

Find the maximum result of ai XOR aj, where 0 ≤ ij < n.

Example:

Input: [3, 10, 5, 25, 2, 8]

Output: 28

Explanation: The maximum result is 5 ^ 25 = 28.


 

class Solution {

    public int findMaximumXOR(int[] nums) {

        int i, j, length = nums.length, max=0;

        for(i=0;i<length;i++){

            int tmp = 0;

            for(j=0;j<length;j++){

                if(i!=j){

                    tmp = nums[i]^nums[j];

                    if(tmp > max){

                        max = tmp;

                    }

                }

            }

        }

     return max;   

    }

}

The above solution is a Brute Force approach.

1) Take i, j for iteration.

2) For each i, do XOR operation with remaining all nums using j (inner loop).

3) Each XOR operation is stored in tmp variable.

4) If tmp is greater than max, then update max variable.

5) Finally return max.


Click Follow button to receive latest updates from us instantly.

Please let us know about your views in comment section.

Like us? Help us to grow...

Help Others, Please Share..!!!!

                                                     😍..Happy Coding...😍

Comments

Popular posts from this blog

First Unique Character in a String

Balanced Binary Tree

Majority Element

Sequential Digits