| | | 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.ReorderedPowerOfTwo; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class ReorderedPowerOfTwoFrequencyArray : IReorderedPowerOfTwo |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(1) |
| | | 19 | | /// Space complexity - O(1) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="n"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public bool ReorderedPowerOf2(int n) |
| | 13 | 24 | | { |
| | 13 | 25 | | var targetDigitsFrequency = GetDigitsFrequency(n); |
| | | 26 | | |
| | 448 | 27 | | for (var i = 0; i < 31; i++) |
| | 220 | 28 | | { |
| | 220 | 29 | | var currentDigitsFrequency = GetDigitsFrequency(1 << i); |
| | | 30 | | |
| | 220 | 31 | | if (AreEqual(targetDigitsFrequency, currentDigitsFrequency)) |
| | 9 | 32 | | { |
| | 9 | 33 | | return true; |
| | | 34 | | } |
| | 211 | 35 | | } |
| | | 36 | | |
| | 4 | 37 | | return false; |
| | 13 | 38 | | } |
| | | 39 | | |
| | | 40 | | private static int[] GetDigitsFrequency(int num) |
| | 233 | 41 | | { |
| | 233 | 42 | | var digitsFrequency = new int[10]; |
| | | 43 | | |
| | 1264 | 44 | | while (num > 0) |
| | 1031 | 45 | | { |
| | 1031 | 46 | | digitsFrequency[num % 10]++; |
| | | 47 | | |
| | 1031 | 48 | | num /= 10; |
| | 1031 | 49 | | } |
| | | 50 | | |
| | 233 | 51 | | return digitsFrequency; |
| | 233 | 52 | | } |
| | | 53 | | |
| | | 54 | | private static bool AreEqual(int[] a, int[] b) |
| | 220 | 55 | | { |
| | 822 | 56 | | for (var i = 0; i < 10; i++) |
| | 402 | 57 | | { |
| | 402 | 58 | | if (a[i] != b[i]) |
| | 211 | 59 | | { |
| | 211 | 60 | | return false; |
| | | 61 | | } |
| | 191 | 62 | | } |
| | | 63 | | |
| | 9 | 64 | | return true; |
| | 220 | 65 | | } |
| | | 66 | | } |