| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.MinimizeXOR; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class MinimizeXORBitwise : IMinimizeXOR |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(1) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="num1"></param> |
| | 22 | | /// <param name="num2"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int MinimizeXor(int num1, int num2) |
| 2 | 25 | | { |
| 2 | 26 | | var result = 0; |
| | 27 | |
|
| 2 | 28 | | var num2SetBits = CountSetBits(num2); |
| | 29 | |
|
| 132 | 30 | | for (var i = 31; i >= 0 && num2SetBits > 0; i--) |
| 64 | 31 | | { |
| 64 | 32 | | if ((num1 & (1 << i)) == 0) |
| 61 | 33 | | { |
| 61 | 34 | | continue; |
| | 35 | | } |
| | 36 | |
|
| 3 | 37 | | result |= 1 << i; |
| | 38 | |
|
| 3 | 39 | | num2SetBits--; |
| 3 | 40 | | } |
| | 41 | |
|
| 8 | 42 | | for (var i = 0; i < 32 && num2SetBits > 0; i++) |
| 2 | 43 | | { |
| 2 | 44 | | if ((result & (1 << i)) != 0) |
| 1 | 45 | | { |
| 1 | 46 | | continue; |
| | 47 | | } |
| | 48 | |
|
| 1 | 49 | | result |= 1 << i; |
| | 50 | |
|
| 1 | 51 | | num2SetBits--; |
| 1 | 52 | | } |
| | 53 | |
|
| 2 | 54 | | return result; |
| 2 | 55 | | } |
| | 56 | |
|
| | 57 | | private static int CountSetBits(int n) |
| 2 | 58 | | { |
| 2 | 59 | | var count = 0; |
| | 60 | |
|
| 9 | 61 | | while (n > 0) |
| 7 | 62 | | { |
| 7 | 63 | | count += n & 1; |
| | 64 | |
|
| 7 | 65 | | n >>= 1; |
| 7 | 66 | | } |
| | 67 | |
|
| 2 | 68 | | return count; |
| 2 | 69 | | } |
| | 70 | | } |