MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / minimizeXor

Method minimizeXor

minimizeXor.java:2–25  ·  view source on GitHub ↗
(int num1, int num2)

Source from the content-addressed store, hash-verified

1class Solution {
2 public int minimizeXor(int num1, int num2) {
3 //find set bits in num2
4 int setBits = Integer.bitCount(num2); //n & n-1 logN
5 int bit=31;
6 int res=0;
7 while(bit>=0 && setBits>0){
8 //check if bit is set in num1 and if so, set the bit in res
9 if((num1 & (1 << bit)) !=0){
10 res = res | (1 << bit);
11 setBits--;
12 }
13 bit--;
14 }
15 bit = 0;
16 // 1011001
17 while(setBits>0 && bit<=32){
18 if((num1 & (1 << bit)) == 0){
19 res = res | (1 << bit);
20 setBits--;
21 }
22 bit++;
23 }
24 return res;
25 }
26}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected