| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.ReverseBits; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class ReverseBitsDivideAndConquer : IReverseBits |
| | | 16 | | { |
| | | 17 | | private const int Mask1 = 0x55555555; |
| | | 18 | | private const int Mask2 = 0x33333333; |
| | | 19 | | private const int Mask4 = 0x0F0F0F0F; |
| | | 20 | | private const int Mask8 = 0x00FF00FF; |
| | | 21 | | private const int Mask16 = 0x0000FFFF; |
| | | 22 | | |
| | | 23 | | /// <summary> |
| | | 24 | | /// Time complexity - O(1) |
| | | 25 | | /// Space complexity - O(1) |
| | | 26 | | /// </summary> |
| | | 27 | | /// <param name="n"></param> |
| | | 28 | | /// <returns></returns> |
| | | 29 | | public int ReverseBits(int n) |
| | 2 | 30 | | { |
| | 2 | 31 | | n = ((n >> 1) & Mask1) | ((n & Mask1) << 1); |
| | 2 | 32 | | n = ((n >> 2) & Mask2) | ((n & Mask2) << 2); |
| | 2 | 33 | | n = ((n >> 4) & Mask4) | ((n & Mask4) << 4); |
| | 2 | 34 | | n = ((n >> 8) & Mask8) | ((n & Mask8) << 8); |
| | 2 | 35 | | n = ((n >> 16) & Mask16) | ((n & Mask16) << 16); |
| | | 36 | | |
| | 2 | 37 | | return n; |
| | 2 | 38 | | } |
| | | 39 | | } |