privateintgetMax(int[] nums) { if (nums.length == 0) thrownewIllegalArgumentException(); intmaxVal= nums[0]; for (int val : nums) { maxVal = Math.max(maxVal, val); } return maxVal; }
private String[] getStringArray(int[] nums, int maxLen) { intn= nums.length; String[] result = newString[n]; Stringformat="%" + maxLen + "s"; for (inti=0; i < n; ++i) { result[i] = getBinaryString(nums[i], format); } return result; }
private String getBinaryString(int num, String format) { // or use toString(?, 2) return String.format(format, Integer.toBinaryString(num)).replace(' ', '0'); }
private TrieNode generateTrie(String[] numsArr) { TrieNoderoot=newTrieNode(); for (String s : numsArr) { // for each string TrieNodep= root; // p must be here!!!! for (inti=0; i < s.length(); ++i) { // for each char intnum= s.charAt(i) == '0' ? 0 : 1; if (p.next[num] == null) { p.next[num] = newTrieNode(); } p = p.next[num]; } } return root; }
privateintfindTheOtherInTrie(TrieNode root, int[] nums, String[] numsArr) { intn= nums.length; intmaxXOR= Integer.MIN_VALUE; for (inti=0; i < n; ++i) { Strings= numsArr[i]; StringBuildersb=newStringBuilder(); TrieNodemaxP= root; TrieNodeotherP= root; for (intj=0; j < s.length(); ++j) { intnum= s.charAt(j) == '0' ? 0 : 1; maxP = maxP.next[num]; // try to go to the opposite if possible intdirection= otherP.next[num ^ 1] != null ? (num ^ 1) : num; sb.append(direction); otherP = otherP.next[direction]; } intotherNum= Integer.parseInt(sb.toString(), 2); // convert binary string to integer maxXOR = Math.max(maxXOR, nums[i] ^ otherNum); } return maxXOR; }