| | 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.NumberOfOneBits; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class NumberOfOneBitsLookup : INumberOfOneBits |
| | 16 | | { |
| 1 | 17 | | private static readonly int[] WordBits = new int[65536]; |
| | 18 | |
|
| | 19 | | static NumberOfOneBitsLookup() |
| 1 | 20 | | { |
| | 21 | | uint i; |
| | 22 | |
|
| 131074 | 23 | | for (i = 0; i <= 0xFFFF; i++) |
| 65536 | 24 | | { |
| 65536 | 25 | | var x = i; |
| | 26 | |
|
| | 27 | | int count; |
| | 28 | |
|
| 1179648 | 29 | | for (count = 0; x > 0; count++) |
| 524288 | 30 | | { |
| 524288 | 31 | | x &= x - 1; |
| 524288 | 32 | | } |
| | 33 | |
|
| 65536 | 34 | | WordBits[i] = count; |
| 65536 | 35 | | } |
| 1 | 36 | | } |
| | 37 | |
|
| | 38 | | /// <summary> |
| | 39 | | /// Time complexity - O(1) |
| | 40 | | /// Space complexity - O(1) |
| | 41 | | /// </summary> |
| | 42 | | /// <param name="n"></param> |
| | 43 | | /// <returns></returns> |
| | 44 | | public int HammingWeight(int n) |
| 3 | 45 | | { |
| 3 | 46 | | return WordBits[n & 0xFFFF] + WordBits[(n >> 16) & 0xFFFF]; |
| 3 | 47 | | } |
| | 48 | | } |