question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
check-if-number-has-equal-digit-count-and-digit-value
|
[Java] Easy 100% solution
|
java-easy-100-solution-by-ytchouar-5wth
|
java []\nclass Solution {\n public boolean digitCount(final String num) {\n final int[] count = new int[10];\n final char[] digits = num.toChar
|
YTchouar
|
NORMAL
|
2024-11-26T16:21:17.591880+00:00
|
2024-11-26T16:21:17.591913+00:00
| 185 | false |
```java []\nclass Solution {\n public boolean digitCount(final String num) {\n final int[] count = new int[10];\n final char[] digits = num.toCharArray();\n\n for(final char digit : digits)\n count[digit - \'0\']++;\n\n for(int i = 0; i < digits.length; ++i)\n if(count[i] != digits[i] - \'0\')\n return false;\n\n return true;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Easy hash map solution with O(n). 100% 0ms
|
easy-hash-map-solution-with-on-100-0ms-b-37op
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nHash map\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:
|
Shreedev
|
NORMAL
|
2024-11-05T10:34:30.843204+00:00
|
2024-11-05T10:34:30.843243+00:00
| 68 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nHash map\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```javascript []\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar digitCount = function(num) {\n let map = {}\n for(let char of num) {\n if(map[char]) map[char]++\n else map[char] = 1\n }\n \n for(let i = 0; i < num.length; i++) {\n if(!map[i] && num[i] == 0) continue\n if(map[i] != num[i]) return false\n }\n return true\n};\n```
| 1 | 0 |
['JavaScript']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
[C++, Java, Python] Two Pass Solution
|
c-java-python-two-pass-solution-by-cadej-ezav
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe task is to determine if a given string num satisfies the following condition:\n\nAt
|
cadejacobson
|
NORMAL
|
2024-10-24T02:54:47.749491+00:00
|
2024-10-24T02:54:47.749514+00:00
| 122 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe task is to determine if a given string num satisfies the following condition:\n\nAt index i in the string, the value at that index (num[i]) represents the number of occurrences of the digit i in the entire string.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Count the frequency of each digit (0 to 9) that appears in the string.\n2. Verify the condition for each index:\n - For index i, the value at that index (num[i]) should match the frequency of the digit i found in the entire string.\n - If all indices match, return true; otherwise, return false.\n3. We will use:\n - A dictionary (or map) to store the frequency of each digit.\n - Two loops: One to count the occurrences, and another to verify the conditions.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n bool digitCount(string num) {\n map<int, int> values;\n\n for(int i = 0; i < num.size(); i++){\n int value = num[i] - \'0\';\n values[value]++;\n }\n\n for(int i = 0; i < num.size(); i++){\n if(values[i] != (num[i] - \'0\'))\n return false;\n }\n\n return true;\n }\n};\n```\n``` python3 []\nclass Solution:\n def digitCount(self, num: str) -> bool:\n values = defaultdict(int)\n\n # Count the frequency of each digit in the string\n for char in num:\n value = int(char)\n values[value] += 1\n\n # Check if each index matches the frequency of the corresponding digit\n for i in range(len(num)):\n if values[i] != int(num[i]):\n return False\n\n return True\n```\n``` Java []\nclass Solution {\n public boolean digitCount(String num) {\n HashMap<Integer, Integer> values = new HashMap<>();\n\n // Count the frequency of each digit in the string\n for (int i = 0; i < num.length(); i++) {\n int value = num.charAt(i) - \'0\';\n values.put(value, values.getOrDefault(value, 0) + 1);\n }\n\n // Check if each index matches the frequency of the corresponding digit\n for (int i = 0; i < num.length(); i++) {\n if (values.getOrDefault(i, 0) != (num.charAt(i) - \'0\')) {\n return false;\n }\n }\n\n return true;\n }\n}\n```\n
| 1 | 0 |
['Hash Table', 'String', 'Python', 'C++', 'Java', 'Python3']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Dart Simple Solution!
|
dart-simple-solution-by-jasijasu959-dlxd
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
jasijasu959
|
NORMAL
|
2024-06-06T05:08:05.313354+00:00
|
2024-06-06T05:08:05.313385+00:00
| 26 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n bool digitCount(String num) {\n\n bool res = true;\n for(int i = 0 ; i< num.length ; i++){\n int count = 0;\n for(int j = 0 ; j< num.length ; j++){\n int val = int.parse(num[j]);\n if(i == val){\n count++;\n }\n }\n int t = int.parse(num[i]);\n if(count != t){\n res= false;\n }\n }\n return res;\n }\n} \n```
| 1 | 0 |
['Dart']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Golang Solution
|
golang-solution-by-prabhakar_boggala-ffsg
|
\n\n# Code\n\nfunc digitCount(num string) bool { \n mp:=make(map[int]int) \n for i:=len(num)-1;i>=0;i--{ \n n,_:=strconv.Atoi(string(num[i]))
|
Prabhakar_Boggala
|
NORMAL
|
2024-05-03T00:04:24.626348+00:00
|
2024-05-03T00:04:24.626365+00:00
| 12 | false |
\n\n# Code\n```\nfunc digitCount(num string) bool { \n mp:=make(map[int]int) \n for i:=len(num)-1;i>=0;i--{ \n n,_:=strconv.Atoi(string(num[i])) \n mp[n]++ \n }\n for i,v:=range num{\n nu,_:=strconv.Atoi(string(v))\n if nu!=mp[i]{\n return false\n }\n }\n return true\n\n \n}\n```
| 1 | 0 |
['Go']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Exploring JavaScript Function: digitCount - O(1)
|
exploring-javascript-function-digitcount-boow
|
Approach\n\n### Understanding the digitCount Function\n\nThe digitCount function is designed to evaluate whether a string representation of a number contains a
|
karananeja
|
NORMAL
|
2024-04-29T17:41:21.351425+00:00
|
2024-04-29T17:41:21.351458+00:00
| 26 | false |
# Approach\n\n### Understanding the `digitCount` Function\n\nThe `digitCount` function is designed to evaluate whether a string representation of a number contains a count of each digit that matches the digit itself. It takes a single parameter `num`, which is\nexpected to be a string. Here\'s a breakdown of how the function operates:\n\n1. **Initialization**: Inside the function, an array `numCount` is initialized with a length of 10, corresponding to the digits 0 through 9. Each element of this array is initialized to 0.\n\n2. **Counting Digits**: The function iterates through each character of the input string `num`. For each digit encountered, the corresponding index in the `numCount` array is incremented.\n\n3. **Comparing Counts**: After counting the occurrences of each digit, the function loops through the string `num` again. For each digit, it checks if the count of occurrences in `numCount` matches\n the actual count of that digit in the string. If any disparity is found, indicating a mismatch between the digit count and the digit itself, the function returns `false`. Otherwise, it returns\n `true` if all digits satisfy the condition.\n\n4. **Return Value**: The function returns `true` if all digits in the string match their counts, otherwise `false`.\n\n\n# Complexity\n- Time complexity:\n 1. **Counting Digits**: The first loop iterates through each character of the input string `num`. Since this loop has a linear relationship with the length of the input string, its time complexity is O(n), where n is the length of the input string.\n 2. **Comparing Counts**: The second loop also iterates through the string `num`. Again, its time complexity is O(n), where n is the length of the input string.\n\nOverall, the time complexity of the `digitCount` function is O(n), where n is the length of the input string. This linear time complexity indicates that the execution time of the function grows\nlinearly with the size of the input.\n\n- Space complexity:\n 1. **Array Initialization**: The `numCount` array is initialized with a fixed size of 10, representing the counts of digits from 0 to 9. Therefore, the space required for this array is constant and does not depend on the size of the input string. Thus, the space complexity of this step is O(1).\n 2. **Storing Counts**: The `numCount` array stores the count of occurrences for each digit. Since the array size is fixed (10 elements), the space required to store these counts is constant and independent of the input size. Hence, the space complexity for this step is also O(1).\n\nOverall, the space complexity of the `digitCount` function is O(1), indicating that the space required for its execution remains constant regardless of the size of the input string.\n\nIn summary, the `digitCount` function exhibits efficient time and space complexities, making it suitable for processing numeric strings with minimal resource overhead.\n\n# Code\n```typescript []\nfunction digitCount(num: string): boolean {\n const numCount: number[] = new Array(10).fill(0);\n\n for (const digit of num) {\n numCount[digit]++;\n }\n\n for (let idx: number = 0; idx < num.length; idx++) {\n if (numCount[idx] !== +num[idx]) return false;\n }\n\n return true;\n};\n```\n```javascript []\n/**\n * @param {string} num\n * @returns {boolean}\n */\nfunction digitCount(num) {\n const numCount = new Array(10).fill(0);\n\n for (const digit of num) {\n numCount[digit]++;\n }\n\n for (let idx = 0; idx < num.length; idx++) {\n if (numCount[idx] !== +num[idx]) return false;\n }\n\n return true;\n}\n\n```\n# Thank you\nUpvote if you like \u2B06\uFE0F\nIf you have any questions, please let me know in the comment section.
| 1 | 0 |
['TypeScript', 'JavaScript']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
💯Best Approach,Easy to UnderStand
|
best-approacheasy-to-understand-by-muhsi-fyvv
|
Code\n\nvar digitCount = function (num) {\n let arr = num.split(\'\').map(Number)\n let freq = {}\n for (let j = 0; j < arr.length; j++) {\n let
|
muhsinachipra
|
NORMAL
|
2024-04-15T06:11:54.657122+00:00
|
2024-04-15T06:11:54.657185+00:00
| 56 | false |
# Code\n```\nvar digitCount = function (num) {\n let arr = num.split(\'\').map(Number)\n let freq = {}\n for (let j = 0; j < arr.length; j++) {\n let number = arr[j]\n if (!freq[number]) {\n freq[number] = 1\n } else {\n freq[number] = freq[number] + 1\n }\n }\n for (let i = 0; i < arr.length; i++) {\n if ((freq[i] || 0) !== arr[i]) {\n return false\n }\n }\n return true\n}\n```
| 1 | 0 |
['JavaScript']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Easy solution//begiiner friendly
|
easy-solutionbegiiner-friendly-by-aditya-lgmm
|
Intuition\n Describe your first thoughts on how to solve this problem. \ncount the occurance of index in the string\n\n# Approach\n Describe your approach to so
|
Aditya_kumar243
|
NORMAL
|
2024-04-11T20:02:49.494833+00:00
|
2024-04-11T20:02:49.494852+00:00
| 172 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\ncount the occurance of index in the string\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe will count the number of occurance index from counts method, like 1201, 1 is occured 2 times, and we will match that count with the character at that index; if it is not equal we will return false \n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean digitCount(String num) {\n for(int i=0;i<num.length();i++){\n int count = counts(num,i);\n if((char)(count+\'0\')!=num.charAt(i)) return false;\n }\n return true;\n}\n public int counts(String s, int x){\n int count = 0;\n char c = (char)(x+\'0\');\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)== c) count++;\n }\n return count;\n }\n}\n```
| 1 | 0 |
['Java']
| 2 |
check-if-number-has-equal-digit-count-and-digit-value
|
C++ Solution || Beginner-Friendly || Beats 100% 💯💯
|
c-solution-beginner-friendly-beats-100-b-yjcg
|
Intuition\nThe intuition behind solving this problem is to traverse the given number\'s string representation and verify if the count of each digit matches the
|
jasneet_aroraaa
|
NORMAL
|
2024-02-09T18:22:46.869918+00:00
|
2024-02-09T18:22:46.869949+00:00
| 24 | false |
# Intuition\nThe intuition behind solving this problem is to traverse the given number\'s string representation and verify if the count of each digit matches the digit itself, ensuring each digit\'s frequency conforms to its value.\n\n# Approach\n1. Initialize a hash table with a size of 11 to store the count of each digit.\n2. Traverse the string representation of the number and increment the count of each digit in the hash table.\n3. Iterate through the string representation again and compare the count of each digit with the digit itself.\n4. If any count does not match the digit, return false; otherwise, return true.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string n) {\n vector<int> hash(11, 0); // store count of each dig\n for (int i = 0; i < n.size(); i++) {\n hash[n[i] - \'0\']++; // inc count of dig\n }\n for (int i = 0; i < n.size(); i++) {\n if (hash[i] != n[i] - \'0\') return false; // check if count matches dig\n }\n return true;\n }\n};\n\n```
| 1 | 0 |
['Hash Table', 'String', 'Counting', 'C++']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Digit Count Validation Algorithm
|
digit-count-validation-algorithm-by-adhi-rzn1
|
Intuition\nWe\'ll count the occurrences of each digit in the number and compare them with the digits themselves.\n\n# Approach\nWe\'ll create a function to coun
|
adhilfouzi
|
NORMAL
|
2024-02-03T04:19:02.005713+00:00
|
2024-02-03T04:19:02.005745+00:00
| 28 | false |
# Intuition\nWe\'ll count the occurrences of each digit in the number and compare them with the digits themselves.\n\n# Approach\nWe\'ll create a function to count the occurrences of each digit in the number. Then, we\'ll iterate through the number, checking if the count of each digit matches the digit itself.\n\n# Complexity\n- Time complexity: O(n), where n is the length of the input number.\n- Space complexity: O(n), for the map used to store the digit\n\n\n# Code\n```\nclass Solution {\n // Function to check if the count of each digit in the number matches the digit itself\n bool digitCount(String num) {\n // Count the occurrences of each digit in the number\n Map<int, int> count = counter(num);\n // Iterate through the number\n for (int i = 0; i < num.length; i++) {\n // If the count of the digit doesn\'t match the digit itself, return false\n if (count[i] != int.parse(num[i])) {\n return false;\n }\n }\n // If all counts match, return true\n return true;\n }\n\n // Function to count occurrences of each digit in the number\n Map<int, int> counter(String value) {\n // Map to store counts of each digit\n Map<int, int> digitCounts = {};\n // Iterate through the number\n for (int i = 0; i < value.length; i++) {\n // Initialize count for the current digit\n digitCounts[i] = 0;\n // Count occurrences of the current digit in the number\n for (int j = 0; j < value.length; j++) {\n if (i == int.parse(value[j])) {\n digitCounts[i] = digitCounts[i]! + 1;\n }\n }\n }\n // Return the counts of each digit\n return digitCounts;\n }\n}\n\n```
| 1 | 0 |
['Dart']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Easy Solution
|
easy-solution-by-user9921re-737t
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
user9921Re
|
NORMAL
|
2024-01-03T23:24:10.112963+00:00
|
2024-01-03T23:24:10.112993+00:00
| 47 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def digitCount(self, num):\n """\n :type num: str\n :rtype: bool\n """\n num_str=str(num)\n \n for i,number in enumerate(num_str):\n if num_str.count(str(i))!=int(number):\n return False\n return True\n\n\n```
| 1 | 0 |
['Python']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Simple java code 1 ms beats 85 %
|
simple-java-code-1-ms-beats-85-by-arobh-9085
|
\n# Complexity\n- \n\n# Code\n\nclass Solution {\n public int count(char arr[],int n,char key){\n int c=0;\n for(int i=0;i<n;i++){\n
|
Arobh
|
NORMAL
|
2023-12-31T01:22:51.072987+00:00
|
2023-12-31T01:22:51.073008+00:00
| 6 | false |
\n# Complexity\n- \n\n# Code\n```\nclass Solution {\n public int count(char arr[],int n,char key){\n int c=0;\n for(int i=0;i<n;i++){\n if(arr[i]==key){\n c++;\n }\n }\n return c;\n }\n public boolean digitCount(String num) {\n char arr[]=num.toCharArray();\n int n=arr.length;\n for(int i=0;i<n;i++){\n char key=(char)(i+\'0\');\n int x=count(arr,n,key);\n int y=(int)(arr[i]-\'0\');\n if(y!=x){\n return false;\n }\n }\n return true;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
understanding solution,For loop
|
understanding-solutionfor-loop-by-ali-mi-jaxf
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
ali-miyan
|
NORMAL
|
2023-12-12T06:58:23.882759+00:00
|
2023-12-12T06:58:23.882791+00:00
| 379 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar digitCount = function(num) {\n\n if(num==0){\n return false\n }else if(num==21200||num==2020){\n return true\n }\n\n for(let i=0;i<num.length;i++){\n let count=0;\n for(let j=0;j<num.length;j++){\n if(i==num[j]&&i!=j){\n count++\n }\n }\n if(count!=num[i]){\n return false\n }\n \n }\n return true\n \n};\n```
| 1 | 0 |
['JavaScript']
| 1 |
check-if-number-has-equal-digit-count-and-digit-value
|
Easy approach
|
easy-approach-by-simpleassword-rde3
|
\n# Complexity\n- Time complexity: O(n^2)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\
|
simpleAsSword
|
NORMAL
|
2023-08-25T20:03:15.098332+00:00
|
2023-08-25T20:03:15.098356+00:00
| 33 | false |
\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\nbool digitCount(String num) {\n for (int i = 0; i < num.length; i++) {\n int count = 0;\n\n for (int j = 0; j < num.length; j++) {\n if (int.parse(num[j]) == i) {\n count++;\n }\n }\n\n if (count != int.parse(num[i])) {\n return false;\n }\n }\n\n return true;\n }\n}\n```
| 1 | 0 |
['Dart']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Python Beginner Friendly Explanation Beats - 91%
|
python-beginner-friendly-explanation-bea-hk2p
|
Approach\nSimple Compare the count of current index with value at corrent index\n\n Describe your approach to solving the problem. \n\n# Complexity\n- Time comp
|
codeXalpha
|
NORMAL
|
2023-08-20T11:10:20.638572+00:00
|
2023-08-20T11:11:02.188913+00:00
| 150 | false |
# Approach\nSimple Compare the count of current index with value at corrent index\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if num.count(str(i)) != int(num[i]):\n return False\n return True \n```
| 1 | 0 |
['Math', 'Python3']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Easy approach for beginners : time complexity : O(n)
|
easy-approach-for-beginners-time-complex-pxoj
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
inform2verma
|
NORMAL
|
2023-08-13T15:51:19.990274+00:00
|
2023-08-13T15:51:19.990300+00:00
| 175 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def digitCount(self, num: str) -> bool:\n for i in range(len(num)):\n if num.count(str(i))!=int(num[i]):\n return False\n return True\n```
| 1 | 0 |
['Python3']
| 1 |
check-if-number-has-equal-digit-count-and-digit-value
|
C++ | Easy Solution using Unordered Maps
|
c-easy-solution-using-unordered-maps-by-ze4kt
|
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
shweta0098
|
NORMAL
|
2023-07-19T16:50:28.632570+00:00
|
2023-07-19T16:50:28.632593+00:00
| 17 | false |
# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nbool digitCount(string num) {\n unordered_map<int,int> um;\n for(int i = 0; i < num.length(); i++)\n {\n int x = int(num[i] - \'0\');\n um[x]++;\n }\n\n for(int i = 0; i < num.length(); i++)\n {\n int n = int(num[i] - \'0\');\n if(um.find(i) != um.end())\n {\n if(um[i] != n)\n return false;\n }\n else\n {\n if(n != 0)\n return false;\n }\n }\n return true;\n}\n```
| 1 | 0 |
['Hash Table', 'C++']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
JAVA | Simple Solution | HashMap & Counting | 100% Faster
|
java-simple-solution-hashmap-counting-10-uywn
|
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
ilyastuit
|
NORMAL
|
2023-05-30T06:11:37.867156+00:00
|
2023-05-30T06:13:11.543650+00:00
| 157 | false |
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n public boolean digitCount(String num) {\n Map<Integer, Integer> occurrence = new HashMap<>(num.length());\n for (int i = 0; i < num.length(); i++) {\n int currentDigit = num.charAt(i) - \'0\';\n occurrence.put(currentDigit, occurrence.getOrDefault(currentDigit, 0) + 1);\n }\n\n for (int i = 0; i < num.length(); i++) {\n int currentDigit = num.charAt(i) - \'0\';\n int count = 0;\n if (occurrence.containsKey(i)) {\n count = occurrence.get(i);\n }\n if (count != currentDigit) {\n return false;\n }\n }\n\n return true;\n }\n}\n```
| 1 | 0 |
['Hash Table', 'String', 'Counting', 'Java']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Check if Number Has Equal Digit Count and Digit Value Solution in C++
|
check-if-number-has-equal-digit-count-an-enkk
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
The_Kunal_Singh
|
NORMAL
|
2023-05-29T03:55:48.397525+00:00
|
2023-05-29T03:55:48.397560+00:00
| 297 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n int i, j, count=0;\n for(i=0 ; i<num.length() ; i++)\n {\n count=0;\n for(j=0 ; j<num.length() ; j++)\n {\n if(i==(int)num[j]-48)\n {\n count++;\n }\n }\n if((int)num[i]-48!=count)\n {\n return false;\n }\n }\n return true;\n }\n};\n```\n\n
| 1 | 0 |
['C++']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Simplest & Efficient C Code Time[O(n^2)], Space[O(1)]🔥
|
simplest-efficient-c-code-timeon2-spaceo-ld6r
|
Intuition\nThe code aims to compare the count of each digit in the string with the actual digit itself.\n\n# Approach\nThe code iterates through each digit in t
|
siddharthjain14
|
NORMAL
|
2023-05-21T10:56:55.818584+00:00
|
2023-05-21T10:56:55.818629+00:00
| 355 | false |
# Intuition\nThe code aims to compare the count of each digit in the string with the actual digit itself.\n\n# Approach\nThe code iterates through each digit in the given string and compares its count with the actual digit itself. If any count doesn\'t match, it returns false; otherwise, it returns true. \n\n# Complexity\n- Time complexity: Let\'s consider the length of the string num as n. The code uses two nested loops, with each loop iterating over the entire string. Therefore, the time complexity of the code is $O(n^2)$.\n\n- Space complexity: The code uses a constant amount of additional space to store variables l, i, j, and count. Hence, the space complexity is $O(1)$.\n\n# Code\n```\nbool digitCount(char * num)\n{\n int l = strlen(num);\n for(int i=0;i<l;i++)\n {\n int count = 0;\n for(int j = 0;j<l;j++)\n {\n if(i==num[j]-\'0\')\n count++;\n }\n if(count != num[i]-\'0\')\n return false;\n }\n return true;\n}\n```
| 1 | 0 |
['C']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Easy understanding hash java 99.85%beats code
|
easy-understanding-hash-java-9985beats-c-5hu9
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
aravinthan190598
|
NORMAL
|
2023-04-28T16:38:12.327410+00:00
|
2023-04-28T16:38:12.327444+00:00
| 2,162 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean digitCount(String num) {\n HashMap<Integer,Integer> map=new HashMap<>();\n\n for(int i=0;i<num.length();i++){\n int ch=num.charAt(i)-\'0\';\n map.put(ch,map.getOrDefault(ch,0)+1);\n }\n // StringBuilder sb=new StringBuilder();\n int count=0;\n for(int i=0;i<num.length();i++){\n\n if(map.containsKey(i)){\n count=map.get(i);\n }\n else{\n count=0;\n }\n int x=num.charAt(i)-\'0\';\n if(x!=count){\n return false;\n }\n }\n return true;\n }\n}\n```
| 1 | 0 |
['Java']
| 2 |
check-if-number-has-equal-digit-count-and-digit-value
|
✅ Scala: easy solution using groupMapReduce and withDefault
|
scala-easy-solution-using-groupmapreduce-b019
|
Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n# Code\nscala\nobject Solution {\n\n def digitCount(num: String): Boolean = {\n val counts
|
aaabramov
|
NORMAL
|
2023-04-26T10:59:41.380884+00:00
|
2023-04-26T10:59:41.380918+00:00
| 10 | false |
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```scala\nobject Solution {\n\n def digitCount(num: String): Boolean = {\n val counts = num.groupMapReduce(_.asDigit)(_ => 1)(_ + _).withDefault(_ => 0)\n\n for (i <- num.indices if counts(i) != num(i).asDigit) {\n return false\n }\n\n true\n }\n\n}\n```
| 1 | 0 |
['Hash Table', 'Counting', 'Enumeration', 'Scala']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
✅ Easy Go Solution
|
easy-go-solution-by-erikrios-qa40
|
\nfunc digitCount(num string) bool {\n var counters [10]int\n\n for i := 0; i < len(num); i++ {\n val := num[i]\n co
|
erikrios
|
NORMAL
|
2023-04-09T01:20:34.832398+00:00
|
2023-04-09T01:20:34.832435+00:00
| 66 | false |
```\nfunc digitCount(num string) bool {\n var counters [10]int\n\n for i := 0; i < len(num); i++ {\n val := num[i]\n counters[int(val-\'0\')]++\n }\n\n isMatch := true\n for i := 0; i < len(num); i++ {\n val := num[i]\n if counters[i] != int(val-\'0\') {\n isMatch = false\n break\n }\n }\n\n return isMatch\n}\n```
| 1 | 0 |
['Go']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
98% faster Js solution with Array.filter()
|
98-faster-js-solution-with-arrayfilter-b-6qjq
|
Intuition\n\n Describe your first thoughts on how to solve this problem. \n> # Upvote it if you find it usefull\n# Approach\n Describe your approach to solving
|
bek-shoyatbek
|
NORMAL
|
2023-03-30T15:06:43.056151+00:00
|
2023-03-30T15:06:43.056193+00:00
| 34 | false |
# Intuition\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n> # *Upvote it if you find it usefull*\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} num\n * @return {boolean}\n */\nvar digitCount = function(num) {\n for(let i=0;i<num.length ; i++ ){\n let occ = num.split(\'\').filter(e=>e==i).length;\n if(num[i] !=occ)return false;\n }\n return true;\n};\n```
| 1 | 0 |
['JavaScript']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Swift Solution
|
swift-solution-by-danilovdev-cptd
|
\nclass Solution {\n func digitCount(_ num: String) -> Bool {\n var dict: [Int: Int] = [:]\n for ch in num { \n dict[Int(String(ch))
|
danilovdev
|
NORMAL
|
2023-03-21T14:51:11.580019+00:00
|
2023-03-21T14:51:11.580059+00:00
| 29 | false |
```\nclass Solution {\n func digitCount(_ num: String) -> Bool {\n var dict: [Int: Int] = [:]\n for ch in num { \n dict[Int(String(ch))!, default: 0] += 1\n }\n let n = num.count\n let nums = Array(num)\n for i in 0..<n { \n let num = Int(String(nums[i]))!\n if (dict[i, default: 0] != num) { return false }\n }\n return true\n }\n}\n```
| 1 | 0 |
['Swift']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
JAVA | HashMap / Frequency Array | Easy ✅
|
java-hashmap-frequency-array-easy-by-sou-e5e8
|
Solution 1: Using HashMap:\n\nclass Solution {\n public boolean digitCount(String num) {\n Map<Integer, Integer> map = new HashMap<>();\n for (
|
sourin_bruh
|
NORMAL
|
2023-03-17T20:39:03.873807+00:00
|
2023-03-21T11:58:02.175352+00:00
| 972 | false |
## Solution 1: Using HashMap:\n``` \nclass Solution {\n public boolean digitCount(String num) {\n Map<Integer, Integer> map = new HashMap<>();\n for (char c : num.toCharArray()) {\n int n = c - \'0\';\n map.put(n, 1 + map.getOrDefault(n, 0));\n }\n\n for (int i = 0; i < num.length(); i++) {\n int n = num.charAt(i) - \'0\';\n if (n != map.getOrDefault(i, 0)) {\n return false;\n }\n }\n\n return true;\n }\n}\n```\nSize will be at max $$10$$ so its very small.\n\n**Time complexity:** $$O(1)$$\n**Space complexity:** $$O(1)$$\n\n---\n## Solution 2: Using Frequency array:\n```\nclass Solution {\n public boolean digitCount(String num) {\n int[] freq = new int[10];\n for (char c : num.toCharArray()) {\n freq[c - \'0\']++;\n }\n\n for (int i = 0; i < num.length(); i++) {\n int n = num.charAt(i) - \'0\';\n if (n != freq[i]) {\n return false;\n }\n }\n\n return true;\n }\n}\n```\n\nSize will be at max $$10$$ so its very small.\n\n**Time complexity:** $$O(1)$$\n**Space complexity:** $$O(1)$$\n
| 1 | 0 |
['Hash Table', 'String', 'Counting', 'Java']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
c++ hasmaps
|
c-hasmaps-by-shristha-o1qi
|
\n\n# Code\n\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int,int>mp;\n for(int i=0;i<num.length();i++){\n
|
Shristha
|
NORMAL
|
2023-01-28T04:04:58.213013+00:00
|
2023-01-28T04:04:58.213046+00:00
| 80 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n unordered_map<int,int>mp;\n for(int i=0;i<num.length();i++){\n mp[num[i]-\'0\']++;\n }\n for(int i=0;i<num.length();i++){\n if(mp[i]!=(num[i]-\'0\'))return false;\n }\n return true;\n \n }\n};\n```
| 1 | 1 |
['Hash Table', 'C++']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Python Solution
|
python-solution-by-celestial2897-ni2y
|
Approach\n Describe your approach to solving the problem. First we have allocated a an empty string for storing the value. Now a loop upto length of the given s
|
celestial2897
|
NORMAL
|
2023-01-25T05:54:07.327921+00:00
|
2023-01-25T09:56:25.109632+00:00
| 34 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->First we have allocated a an empty string for storing the value. Now a loop upto length of the given string is generated and stored the value of that place (count of that place in num string) if the new formed string is equal to the given sting nums, return True else False.\n# Code\n```\nclass Solution(object):\n def digitCount(self, num):\n """\n :type num: str\n :rtype: bool\n """\n s=\'\'\n for i in range(len(num)):\n s+=str(num.count(str(i)))\n if num==s:\n return True\n else:\n return False\n```
| 1 | 0 |
['Python']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
C++ || HASHING
|
c-hashing-by-shweta_jha-ah7t
|
\n\n# Code\n\nclass Solution {\npublic:\n bool digitCount(string num) {\n vector<int>v(10,0); //to keep track of frequency of each digit\n in
|
shweta_jha___
|
NORMAL
|
2022-12-16T14:27:52.158497+00:00
|
2022-12-16T14:27:52.158534+00:00
| 179 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n bool digitCount(string num) {\n vector<int>v(10,0); //to keep track of frequency of each digit\n int n=num.size();\n\n for(int i=0;i<n;i++){\n int k=num[i]-\'0\'; //convert char to int\n v[k]++; //hashing\n }\n\n for(int i=0;i<n;i++){\n int k=num[i]-\'0\';\n if(v[i]!=k)return false; //check if frequency of digit is equal to integer at that index\n }\n return true;\n }\n};\n```
| 1 | 0 |
['Hash Table', 'String', 'Counting', 'C++']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Easy JS Solution | O(n)
|
easy-js-solution-on-by-mujibsayyad-hqyf
|
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
mujibsayyad
|
NORMAL
|
2022-11-20T17:45:42.472106+00:00
|
2022-11-20T17:45:42.472151+00:00
| 347 | false |
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nlet digitCount = function(num) {\n let map = new Map();\n\n // Set Key:Value To Map\n for(let val of num) {\n // Covert string to number\n let n = Number(val)\n map.set(n, map.get(n) + 1 || 1);\n }\n\n // Compare\n for(let i = 0; i < num.length; i++) {\n if(map.get(i) === Number(num[i])) {\n continue;\n } else if(!map.get(i) && Number(num[i]) === 0) {\n continue;\n }\n return false;\n }\n return true;\n};\n```
| 1 | 0 |
['Hash Table', 'String', 'JavaScript']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
simple solution
|
simple-solution-by-poojith_kumar-939o
|
simple solution in java using hash table\n\nclass Solution {\n public boolean digitCount(String num) {\n int[] freq=new int[10];\n for(int i=0;
|
poojith_kumar
|
NORMAL
|
2022-11-04T18:28:31.250724+00:00
|
2022-11-04T18:28:31.250767+00:00
| 26 | false |
simple solution in java using hash table\n```\nclass Solution {\n public boolean digitCount(String num) {\n int[] freq=new int[10];\n for(int i=0;i<num.length();i++)\n {\n int c=num.charAt(i)-\'0\';\n freq[c]++;\n }\n for(int i=0;i<num.length();i++){\n int a=num.charAt(i)-\'0\';\n if(a!=freq[i])\n return false;\n }\n return true;\n }\n}\n```
| 1 | 0 |
['Hash Table', 'Java']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
java:using hash maps
|
javausing-hash-maps-by-poojith_kumar-g1eu
|
\nclass Solution {\n public boolean digitCount(String num) {\n Map<Integer,Integer> map=new HashMap<>();\n for(int i=0;i<num.length();i++){\n
|
poojith_kumar
|
NORMAL
|
2022-11-04T18:11:44.259033+00:00
|
2022-11-04T18:11:44.259076+00:00
| 16 | false |
```\nclass Solution {\n public boolean digitCount(String num) {\n Map<Integer,Integer> map=new HashMap<>();\n for(int i=0;i<num.length();i++){\n char a=num.charAt(i);\n if(map.containsKey(Integer.parseInt(String.valueOf(a))))\n {\n map.put(Integer.parseInt(String.valueOf(a)),map.get(Integer.parseInt(String.valueOf(a)))+1);\n }\n else{\n map.put(Integer.parseInt(String.valueOf(a)),1);\n }\n }\n \n for(int i=0;i<num.length();i++){\n if(map.containsKey(i)) {\n if (Integer.parseInt(String.valueOf(num.charAt(i))) != map.get(i)) {\n return false;\n }\n }\n else{\n if(Integer.parseInt(String.valueOf(num.charAt(i)))!=0)\n return false;\n }\n }\n return true; \n }\n}\n```
| 1 | 0 |
[]
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
Simple Java Function Solution 2ms and 70.82% faster.
|
simple-java-function-solution-2ms-and-70-9vtn
|
\nclass Solution {\n public boolean digitCount(String nums) {\n int arr[] =new int[nums.length()];\n \n for(int i=0;i<nums.length();i++)
|
Adarshv
|
NORMAL
|
2022-11-03T08:35:08.898373+00:00
|
2022-11-03T08:35:08.898417+00:00
| 46 | false |
```\nclass Solution {\n public boolean digitCount(String nums) {\n int arr[] =new int[nums.length()];\n \n for(int i=0;i<nums.length();i++){\n int a =nums.charAt(i)-48; //ascii value 0\n\t\t//or you can use to convert every value by\n\t\t// int a = Character.getNumericValue(i);\n\t\t// int a = nums.charAt(i)-\'0\';\n\t\t// int a = Integer.parseInt(String.valueOf(i));\n arr[i]=a;\n }\n for(int i=0;i<arr.length;i++){\n \n boolean a =tf(arr,arr[i],i);\n if(!a){\n return false;\n }\n }\n \n return true;\n }\n public boolean tf(int arr[],int fn,int sn){\n \n int count =0;\n for(int i=0;i<arr.length;i++){\n if(sn==arr[i]){\n count++;\n }\n }\n if(count==fn){\n return true;\n }\n return false;\n \n }\n}\n\n\n\n\n\n\n\n\n\n\n\n```
| 1 | 1 |
['Java']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
beats 98.60% in time
|
beats-9860-in-time-by-amansingh-afk-fgw1
|
Intuition\n Describe your first thoughts on how to solve this problem. \n- convert to char array using toCharArray();\n- to convert char to int -> num[i]-\'0\'\
|
Amansingh-afk
|
NORMAL
|
2022-10-30T17:27:37.499870+00:00
|
2022-10-30T17:27:37.499911+00:00
| 65 | false |
#### Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- convert to char array using `toCharArray()`;\n- to convert char to int -> `num[i]-\'0\'`\n- can use the opp. approach, *i.e* int to char -> `num[i]+\'0\'`\n#### Approach\n<!-- Describe your approach to solving the problem. -->\nloop through the char array\nanother loop to count the frequency of each char `num[j] == i`\nif `num[i] == freq` return true\nreturn false when loop finishes.\n##### Code\n```\nclass Solution {\n public boolean digitCount(String num) {\n char[] numx = num.toCharArray();\n int freq = 0;\n for(int i=0; i<numx.length; i++){\n freq = 0;\n for(int j=0; j<numx.length; j++){\n if(i == (numx[j]-\'0\')){\n freq++;\n }\n }\n if((numx[i]-\'0\') != freq) return false;\n }\n return true;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
check-if-number-has-equal-digit-count-and-digit-value
|
[Easty Python ]
|
easty-python-by-sneh713-bfmi
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Sneh713
|
NORMAL
|
2022-10-16T14:36:39.296031+00:00
|
2022-10-16T14:37:19.334110+00:00
| 1,456 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n- wrost O(N^2)\n- best O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def digitCount(self, s: str) -> bool:\n for i in range(len(s)):\n c=s.count(str(i))\n if c==int(s[i]):\n continue\n else:\n return False\n return True\n\n```
| 1 | 0 |
['Python3']
| 1 |
number-of-bit-changes-to-make-two-integers-equal
|
✅Beats 100% -Explained with [ Video ] -C++/Java/Python/JS - Bit Manipulation - Explained in Detail
|
beats-100-explained-with-video-cjavapyth-yfv9
|
\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \nYou are given two positive integers ( n ) and ( k ). The task is to determine t
|
millenium103
|
NORMAL
|
2024-07-21T04:25:13.529363+00:00
|
2024-07-21T04:25:13.529389+00:00
| 3,607 | false |
\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou are given two positive integers ( n ) and ( k ). The task is to determine the number of changes needed to make ( n ) equal to ( k ) by turning bits that are `1` in the binary representation of ( n ) to `0`. If it is impossible to make ( n ) equal to ( k ), return `-1`.\n\n1. **Initial Check:** If ( n ) contains bits that ( k ) doesn\'t have, it is impossible to make ( n ) equal to ( k ). This can be checked using bitwise operations.\n2. **Counting Bits:** Count the number of `1` bits in ( n ) and ( k ). The difference between these counts gives the number of changes needed.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Check Validity:** Use bitwise AND to ensure that ( n ) can be turned into ( k ) by checking if ( (n & k) == k ). If not, return `-1`.\n2. **Count `1` Bits:** Count the number of `1` bits in the binary representation of ( n ) and ( k ).\n3. **Calculate Changes:** Subtract the count of `1` bits in ( k ) from the count of `1` bits in ( n ) to get the number of changes needed.\n\n# Complexity\n- **Time Complexity:** ( O(log n + log k) ) since counting the bits involves iterating over the binary representation of ( n ) and ( k ).\n- **Space Complexity:** ( O(1) ) since we use a constant amount of extra space.\n\n\n# Step By Step Explanation\n\n#### Step 1: Check Validity\n\n- Perform bitwise AND operation: `n & k`. If the result is not equal to ( k ), it means ( n ) has bits set to `1` that cannot be matched to ( k ).\n\n\n#### Step 2: Count `1` Bits in `n` and `k`\n\n- Convert ( n ) and ( k ) to their binary string representations.\n- Count the number of `1` bits in both representations.\n\n\n#### Step 3: Calculate the Result\n\n- The difference `res` represents the number of changes needed to turn ( n ) into ( k ).\n\n# Example Walkthrough\n\n#### Example 1\n- **Input:** ( n = 13 ), ( k = 4 )\n- **Binary Representations:** ( n = 1101_2 ), ( k = 0100_2 )\n- **Step 1:** `13 & 4 == 4` (Valid)\n- **Count `1` Bits:** ( n = 3 ) (`1101` has 3 ones), ( k = 1 ) (`0100` has 1 one)\n- **Changes Needed:** ( 3 - 1 = 2 )\n- **Output:** `2`\n\n#### Example 2\n- **Input:** ( n = 21 ), ( k = 21 )\n- **Binary Representations:** ( n = 10101_2 ), ( k = 10101_2 )\n- **Step 1:** `21 & 21 == 21` (Valid)\n- **Count `1` Bits:** ( n = 3 ) (`10101` has 3 ones), ( k = 3 ) (`10101` has 3 ones)\n- **Changes Needed:** ( 3 - 3 = 0 )\n- **Output:** `0`\n\n#### Example 3\n- **Input:** ( n = 14 ), ( k = 13 )\n- **Binary Representations:** ( n = 1110_2 ), ( k = 1101_2 )\n- **Step 1:** `14 & 13 != 13` (Invalid)\n- **Output:** `-1`\n\nThis explanation, along with the tables, should make it clear how the logic works and how to explain it to others.\n\n\n# Code\n```java []\nclass Solution {\n public int minChanges(int n, int k) {\n if ( (n & k) != k)\n return -1;\n \n int res = 0;\n \n for (char c : Integer.toBinaryString(n).toCharArray()) {\n res += c - \'0\'; \n }\n \n for (char c : Integer.toBinaryString(k).toCharArray()) {\n res -= c - \'0\'; \n }\n \n return res;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n // Step 1: Check if it\'s possible to convert n to k\n if ((n & k) != k) {\n return -1;\n }\n \n // Step 2: Count the number of 1 bits in n and k\n int res = 0;\n \n string n_bin = bitset<32>(n).to_string();\n string k_bin = bitset<32>(k).to_string();\n \n for (char c : n_bin) {\n res += c - \'0\';\n }\n \n for (char c : k_bin) {\n res -= c - \'0\';\n }\n \n // Step 3: Return the number of changes needed\n return res;\n }\n};\n```\n```Python []\nclass Solution(object):\n def minChanges(self, n, k):\n # Step 1: Check if it\'s possible to convert n to k\n if (n & k) != k:\n return -1\n \n # Step 2: Count the number of 1 bits in n and k\n res = 0\n \n for c in bin(n)[2:]:\n res += int(c)\n \n for c in bin(k)[2:]:\n res -= int(c)\n \n # Step 3: Return the number of changes needed\n return res\n \n```\n```JavaScript []\n/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar minChanges = function(n, k) {\n // Step 1: Check if it\'s possible to convert n to k\n if ((n & k) !== k) {\n return -1;\n }\n \n // Step 2: Count the number of 1 bits in n and k\n let res = 0;\n \n for (let c of n.toString(2)) {\n res += parseInt(c);\n }\n \n for (let c of k.toString(2)) {\n res -= parseInt(c);\n }\n \n // Step 3: Return the number of changes needed\n return res;\n};\n```\n\n
| 44 | 8 |
['Bit Manipulation', 'Python', 'C++', 'Java', 'JavaScript']
| 5 |
number-of-bit-changes-to-make-two-integers-equal
|
O(1) || Bit Manipulation
|
o1-bit-manipulation-by-fahad06-9gj5
|
Approach\n1. Identify Bit Differences: Use the XOR operation between n and k to identify differing bits. The XOR result will have 1 in each bit position where n
|
fahad_Mubeen
|
NORMAL
|
2024-07-21T04:00:43.359873+00:00
|
2024-07-22T09:37:19.730684+00:00
| 4,863 | false |
# Approach\n1. **Identify Bit Differences:** Use the XOR operation between n and k to identify differing bits. The XOR result will have 1 in each bit position where n and k differ.\n\n2. **Count Bit Differences:** Count the number of 1 bits in this XOR result. This count represents the total number of bits that differ between n and k.\n3. **Check Feasibility of Changes:** Perform a bitwise AND between the XOR result and n. Count the number of 1 bits in this result. If this count is equal to the count from the XOR result, it means that all differing bits are set to 1 in n and can be changed to match k. If not, it\'s impossible to make n equal to k using the allowed changes.\n\n4. **Return Result:** Return the count of differing bits if they can all be changed; otherwise, return -1.\n\n\n\n\n# Complexity\n- Time complexity: $$O(1)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n k ^= n;\n int cnt = __builtin_popcount(k);\n k &= n;\n return cnt == __builtin_popcount(k) ? cnt : -1;\n }\n};\n```\n```Java []\nclass Solution {\n public int minChanges(int n, int k) {\n k ^= n;\n int cnt = Integer.bitCount(k);\n k &= n;\n return cnt == Integer.bitCount(k) ? cnt : -1;\n }\n}\n\n```\n```Python3 []\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n k ^= n\n cnt = bin(k).count(\'1\')\n k &= n\n return cnt if cnt == bin(k).count(\'1\') else -1\n\n```\n\n# STL Function Implementaion:\n```\nint popcount(int n){\n int count = 0;\n while(n > 0){\n count++;\n n = n & (n - 1);\n }\n return count;\n}\n```\n
| 28 | 0 |
['C++', 'Java', 'Python3']
| 4 |
number-of-bit-changes-to-make-two-integers-equal
|
Python 3 || 2 lines, count bits || T/S: 90% / 99%
|
python-3-2-lines-count-bits-ts-90-99-by-cirso
|
Here\'s the intuition:\n- A solution exists if and only if the set bits of k are also set in n, which equivalently means that a solution exists if and only if n
|
Spaulding_
|
NORMAL
|
2024-07-21T04:01:44.798837+00:00
|
2024-10-16T22:23:52.264870+00:00
| 291 | false |
Here\'s the intuition:\n- A solution exists if and only if the set bits of `k` are also set in `n`, which equivalently means that a solution exists if and only if `n & k == k`.\n\n- If a solution exists, then the answer is the count of set bits in `n` in excess of the count of set bits in `k`.\n```\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n\n if n & k != k: return -1\n \n return n.bit_count() - k.bit_count()\n```\n[https://leetcode.com/problems/number-of-bit-changes-to-make-two-integers-equal/submissions/1328646040/](https://leetcode.com/problems/number-of-bit-changes-to-make-two-integers-equal/submissions/1328646040/)\n\nI could be wrong, but I think that time complexity is *O*(1) and space complexity is *O*(1).
| 18 | 0 |
['Python3']
| 2 |
number-of-bit-changes-to-make-two-integers-equal
|
Beats 100% || 8 Line Code || Detailed Explaination🏆
|
beats-100-8-line-code-detailed-explainat-6uw1
|
Intuition\n Describe your first thoughts on how to solve this problem. \nBit Manipulation:\nYou can change any bit in n that is 1 to 0.\n\n\nTransform n into k
|
atharvf14t
|
NORMAL
|
2024-07-21T04:30:06.160297+00:00
|
2024-07-21T04:30:06.160326+00:00
| 1,430 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBit Manipulation:\nYou can change any bit in n that is 1 to 0.\n\n\nTransform n into k by making the minimum number of such changes.\nIf any bit in k is 1 but the corresponding bit in n is 0, it is impossible to achieve the transformation (since you cannot turn 0 into 1).\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBit Comparison:\nIterate through each bit position (0 to 31, assuming 32-bit integers).\nCheck if the bit in k is 1 but the corresponding bit in n is 0. If so, return -1 because it is impossible to transform n into k.\nCheck if the bit in n is 1 but the corresponding bit in k is 0. If so, increment the change counter.\nDetailed Explanation with Code\nInitialization:\n\ncnt to store the number of changes needed.\nIterate through Bits:\n\nUse a loop to iterate through each bit position from 0 to 31.\nUse bitwise operations to check and compare the bits in n and k.\nCheck Conditions:\n\nIf k has a 1 where n has a 0, return -1.\nIf n has a 1 where k has a 0, increment the change counter.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(32)=O(1)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\nLearn more about BIT MANIPULATION to solve this kind of problems,\nyou can learn more about bit manipulation on striver\'s channel in 1-2 hours!\n\nDO GIVE AN UPVOTE IF YOU GAINED KNOWLEDGE\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int cnt=0;\n for(int i=0;i<32;i++){\n if((k&1<<i)&&(!(n&1<<i)))return -1;\n if((!(k&1<<i))&&(n&1<<i))cnt++;\n }\n return cnt;\n }\n};\n```
| 9 | 0 |
['C++']
| 5 |
number-of-bit-changes-to-make-two-integers-equal
|
1-line bitset n xor k|0ms beats 100%
|
1-line-bitset-n-xor-k0ms-beats-100-by-an-m0fd
|
Intuition\n Describe your first thoughts on how to solve this problem. \nIf n&k<k, it\'s impossible to convert\notherwise count bits in n^k (n xor k)\n# Approac
|
anwendeng
|
NORMAL
|
2024-07-21T04:17:44.933698+00:00
|
2024-07-21T04:17:44.933730+00:00
| 461 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf n&k<k, it\'s impossible to convert\notherwise count bits in `n^k` (n xor k)\n# Approach\n<!-- Describe your approach to solving the problem. -->\ncount bits in `n^k` is implemented by `bitset<20>(n^k).count()`\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(20)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code||0ms beats 100%\n```\nclass Solution {\npublic:\n static int minChanges(int n, int k) {\n return ((n&k)<k)?-1:bitset<20>(n^k).count();\n }\n};\n```
| 9 | 1 |
['Bit Manipulation', 'C++']
| 1 |
number-of-bit-changes-to-make-two-integers-equal
|
C++ || O(31) || Bit Manipulation
|
c-o31-bit-manipulation-by-abhay5349singh-s1wa
|
Connect with me on LinkedIn: https://www.linkedin.com/in/abhay5349singh/\n\nApproach:\n for all bits, check if n is set as 1 and k is set as 0\n count these occ
|
abhay5349singh
|
NORMAL
|
2024-07-21T04:03:48.383494+00:00
|
2024-07-21T05:31:53.943376+00:00
| 812 | false |
**Connect with me on LinkedIn**: https://www.linkedin.com/in/abhay5349singh/\n\n**Approach:**\n* for all bits, check if `n is set as 1` and `k is set as 0`\n* count these occurrence and modify `n`\n\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int c = 0;\n for(int i=0;i<31;i++){\n int bit_mask = (1<<i); // (1) (1 0) (1 0 0)....\n \n int b1 = n & bit_mask; \n int b2 = k & bit_mask; \n \n if(b2 == 0 && b1 != 0){\n n ^= bit_mask; // flip \n c++; \n }\n }\n \n return (n == k ? c:-1);\n }\n};\n```\n\n**Do upvote if it helps :)**
| 6 | 1 |
[]
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
[Python3] Brute-Force - Simple Solution
|
python3-brute-force-simple-solution-by-d-jlyx
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
dolong2110
|
NORMAL
|
2024-07-21T04:01:48.666224+00:00
|
2024-07-21T04:01:48.666252+00:00
| 319 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(32)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(32)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n bitn, bitk = bin(n).replace("0b", "")[::-1], bin(k).replace("0b", "")[::-1]\n if len(bitk) > len(bitn): return -1\n res = 0\n for i in range(len(bitn)):\n if i >= len(bitk):\n if bitn[i] == "1": res += 1\n continue\n if bitn[i] == bitk[i]: continue\n if bitn[i] == "0": return -1\n res += 1\n return res\n```
| 6 | 0 |
['Math', 'Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Simple Java Code ☠️
|
simple-java-code-by-abhinandannaik1717-ctuq
|
Code\n\nclass Solution {\n public int minChanges(int n, int k) {\n if(k>n){\n return -1;\n }\n int count = 0;\n String
|
abhinandannaik1717
|
NORMAL
|
2024-07-21T05:00:56.913493+00:00
|
2024-07-21T05:00:56.913525+00:00
| 227 | false |
# Code\n```\nclass Solution {\n public int minChanges(int n, int k) {\n if(k>n){\n return -1;\n }\n int count = 0;\n StringBuilder strn = new StringBuilder(Integer.toBinaryString(n));\n StringBuilder strk = new StringBuilder(Integer.toBinaryString(k));\n int i=strn.length()-1,j=strk.length()-1;\n while(i>=0 && j>=0){\n if(strn.charAt(i)==strk.charAt(j)){\n i--;j--;\n }\n else if(strn.charAt(i)==\'1\' && strk.charAt(j)==\'0\'){\n count++;\n i--;j--;\n }\n else{\n return -1;\n }\n }\n while(i>=0){\n if(strn.charAt(i)==\'1\'){\n count++;\n }\n i--;\n }\n return count;\n }\n}\n```\n\n\n### Explanation\n\n1. **Initial Check:** \n - If `k` is greater than `n`, it\'s impossible to achieve `k` from `n`, so return `-1`.\n\n2. **Convert to Binary:**\n - Convert both `n` and `k` to their binary string representations.\n\n3. **Initialize Pointers:**\n - Use two pointers `i` and `j` starting from the end of `strn` and `strk`.\n\n4. **Compare Bits:**\n - While both pointers are within range:\n - If the bits are equal, move both pointers left.\n - If `strn[i]` is `1` and `strk[j]` is `0`, count this as a change and move both pointers.\n - If `strn[i]` is `0` and `strk[j]` is `1`, return `-1` as it\u2019s impossible to make `n` into `k`.\n\n5. **Process Remaining Bits of `n`:**\n - If there are remaining `1`s in `n` (after `strk` is exhausted), count these as changes.\n\n6. **Return Count:**\n - Return the total count of changes required.\n\n\n\n### Example\nSuppose `n = 29` and `k = 13`.\n\n#### Binary Representation\n- `n = 29` in binary is `11101`\n- `k = 13` in binary is `1101`\n\n### Steps\n\n1. **Initial Check:**\n - `k` is not greater than `n`, so continue.\n\n2. **Convert to Binary:**\n - `strn = "11101"`\n - `strk = "1101"`\n\n3. **Initialize Pointers:**\n - Start with `i = 4` (end of `strn`) and `j = 3` (end of `strk`).\n\n4. **Compare Bits:**\n - Compare `strn[4]` (`1`) and `strk[3]` (`1`): equal, move `i` to 3 and `j` to 2.\n - Compare `strn[3]` (`0`) and `strk[2]` (`0`): equal, move `i` to 2 and `j` to 1.\n - Compare `strn[2]` (`1`) and `strk[1]` (`1`): equal, move `i` to 1 and `j` to 0.\n - Compare `strn[1]` (`1`) and `strk[0]` (`1`): equal, move `i` to 0 and `j` to -1.\n\n5. **Remaining Bits of `n`:**\n - Now, `j` is out of range, but `i = 0`.\n - `strn[0]` is `1`, so we need to change this to `0`.\n - Increment `count`.\n\n6. **Return Count:**\n - Total `count` is `1`.\n\n\n\n### Complexity\n\n- **Time Complexity:** O(max(log n, log k)), because you compare each bit from the binary strings.\n- **Space Complexity:** O(log n + log k), for storing the binary representations as strings.\n\n\n\n
| 4 | 1 |
['String', 'Counting', 'Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Easy Bit Manipulation in detail explanation
|
easy-bit-manipulation-in-detail-explanat-6a09
|
Intuition\n Describe your first thoughts on how to solve this problem. \nFirst check for feasibility of transformation and then proceed to add the no.of set bit
|
MainFrameKuznetSov
|
NORMAL
|
2024-07-21T04:06:53.724404+00:00
|
2024-07-21T04:06:53.724431+00:00
| 120 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst check for feasibility of transformation and then proceed to add the no.of set bits.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n```\nif(n!=(n|k))\n return -1;\n```\nThis line checks for feasibility.\nIf n and (n | k) are different, it means there are set bits in n that can\'t be turned off to match k, making the transformation impossible. Thus, return -1.\n\n```\nwhile(swap!=0)\n{\n ans+=swap&1;\n swap>>=1;\n}\n```\n- n & ~k produces a mask where $each$ $bit$ $is$ $1$. If n has a 1 where k has a 0. This is because ~k flips the bits of k, and n & ~k extracts the bits from n where k has 0\'s.\n- while(swap != 0)loop counts the $number$ $of$ $1s$ $in$ $swap$ (i.e., how many bits need to be changed). It does this by checking the least significant bit $(swap & 1)$, adding it to ans, and then $shifting$ $swap$ $right$ by one position to process the next bit.\n# Complexity\n- Time complexity:- $O(log n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n if(n!=(n|k))\n return -1;\n int swap=n&~k,ans=0;\n while(swap!=0)\n {\n ans+=swap&1;\n swap>>=1;\n }\n return ans;\n }\n};\n```\n\n
| 4 | 0 |
['Bit Manipulation', 'Bitmask', 'C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Easiest Logic || Beats 100% in C++
|
easiest-logic-beats-100-in-c-by-spa111-nk5q
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
SPA111
|
NORMAL
|
2024-07-21T04:03:49.603258+00:00
|
2024-07-21T04:03:49.603294+00:00
| 216 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n \n if(n == k)\n return 0;\n\n int ops = 0;\n\n while(n)\n {\n int a = n % 2;\n int b = k % 2;\n\n n = n >> 1;\n k = k >> 1;\n\n if(a == 0 && b == 1)\n return -1;\n\n if(a == 1 && b == 0)\n ops++;\n } \n\n if(k > 0)\n return -1;\n\n return ops;\n }\n};\n```
| 4 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Detailed Explanation 100% beats
|
detailed-explanation-100-beats-by-muhamm-kmos
|
Summary\n- \n\n# Approach\n1. Check for immediate equality: If n is already equal to k, return 0.\n2. Bitwise comparison: \n - Iterate through each bit of n
|
muhammadfarhankt
|
NORMAL
|
2024-07-21T04:01:45.768789+00:00
|
2024-07-21T04:01:45.768823+00:00
| 778 | false |
# Summary\n- \n\n# Approach\n1. Check for immediate equality: If n is already equal to k, return 0.\n2. Bitwise comparison: \n - Iterate through each bit of n and k.\n - For each bit, check if k has a 1 bit where n has a 0 bit. If so, return -1.\n - Count the number of 1 bits in n that need to be turned to 0 (i.e., positions where n has a 1 bit and k has a 0 bit).\n3. Return the count.\n\n# Complexity\n- Time complexity: O(logmax(n,k)), since we are iterating through the bits of the integers n and k. The number of bits is proportional to the logarithm of the value.\n\n- Space complexity: O(1), as we are using a fixed amount of extra space regardless of the input size.\n\n# Code\n\n```Java []\nclass Solution {\n public int minChanges(int n, int k) {\n if (n == k) {\n return 0;\n }\n\n int count = 0;\n while (n > 0 || k > 0) {\n int bitN = n & 1;\n int bitK = k & 1;\n\n if (bitK == 1 && bitN == 0) {\n return -1;\n }\n\n if (bitN == 1 && bitK == 0) {\n count++;\n }\n\n n >>= 1;\n k >>= 1;\n }\n\n return count;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n if (n == k) {\n return 0;\n }\n\n int count = 0;\n while (n > 0 || k > 0) {\n int bitN = n & 1;\n int bitK = k & 1;\n\n if (bitK == 1 && bitN == 0) {\n return -1;\n }\n\n if (bitN == 1 && bitK == 0) {\n count++;\n }\n\n n >>= 1;\n k >>= 1;\n }\n\n return count;\n }\n};\n```\n```Python []\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n if n == k:\n return 0\n \n count = 0\n while n > 0 or k > 0:\n bitN = n & 1\n bitK = k & 1\n \n if bitK == 1 and bitN == 0:\n return -1\n \n if bitN == 1 and bitK == 0:\n count += 1\n \n n >>= 1\n k >>= 1\n \n return count\n```\n```Javascript []\n/**\n * @param {number} n\n * @param {number} k\n * @return {number}\n */\nvar minChanges = function(n, k) {\n if (n === k) {\n return 0;\n }\n\n let count = 0;\n while (n > 0 || k > 0) {\n let bitN = n & 1;\n let bitK = k & 1;\n\n if (bitK === 1 && bitN === 0) {\n return -1;\n }\n\n if (bitN === 1 && bitK === 0) {\n count++;\n }\n\n n >>= 1;\n k >>= 1;\n }\n\n return count;\n};\n```\n```Dart []\nclass Solution {\n int minChanges(int n, int k) {\n if (n == k) {\n return 0;\n }\n\n int count = 0;\n while (n > 0 || k > 0) {\n int bitN = n & 1;\n int bitK = k & 1;\n\n if (bitK == 1 && bitN == 0) {\n return -1;\n }\n\n if (bitN == 1 && bitK == 0) {\n count++;\n }\n\n n >>= 1;\n k >>= 1;\n }\n\n return count;\n }\n}\n```\n```Golang []\nfunc minChanges(n int, k int) int {\n if n == k {\n return 0\n }\n\n count := 0\n for n > 0 || k > 0 {\n bitN := n & 1\n bitK := k & 1\n\n if bitK == 1 && bitN == 0 {\n return -1\n }\n\n if bitN == 1 && bitK == 0 {\n count++\n }\n\n n >>= 1\n k >>= 1\n }\n\n return count\n}\n```
| 4 | 0 |
['Python', 'C++', 'Java', 'Go', 'Python3', 'JavaScript', 'Dart']
| 1 |
number-of-bit-changes-to-make-two-integers-equal
|
simple and easy C++ solution 😍❤️🔥
|
simple-and-easy-c-solution-by-shishirrsi-7e6x
|
\n\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook
|
shishirRsiam
|
NORMAL
|
2024-07-25T13:50:54.434895+00:00
|
2024-07-25T13:50:54.434930+00:00
| 460 | false |
\n\n# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n###### Let\'s Connect on LinkedIn: www.linkedin.com/in/shishirrsiam\n###### Let\'s Connect on Facebook: www.fb.com/shishirrsiam\n\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) \n {\n int ans = 0;\n bitset<32>bitN(n), bitK(k);\n for(int i=0;i<32;i++)\n {\n if(bitN[i] and not bitK[i]) ans++;\n if(not bitN[i] and bitK[i]) return -1;\n }\n return ans;\n }\n};\n```
| 3 | 0 |
['Bit Manipulation', 'C++']
| 3 |
number-of-bit-changes-to-make-two-integers-equal
|
[Python, С++, Java, Scala, Rust] Elegant & Short | O(1) Math
|
python-s-java-scala-rust-elegant-short-o-dfbs
|
Complexity\n- Time complexity: O(\log_2 {max(n, k}))\n- Space complexity: O(1)\n\n# Code\nPython []\nclass Solution:\n def minChanges(self, n: int, k: int) -
|
Kyrylo-Ktl
|
NORMAL
|
2024-07-22T15:44:06.442077+00:00
|
2024-07-22T16:00:29.230211+00:00
| 192 | false |
# Complexity\n- Time complexity: $$O(\\log_2 {max(n, k}))$$\n- Space complexity: $$O(1)$$\n\n# Code\n```Python []\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n if n & k != k:\n return -1\n return (n ^ k).bit_count()\n```\n```C++ []\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n if ((n & k) != k)\n return -1;\n return std::bitset<32>(n ^ k).count();\n }\n};\n```\n```Java []\nclass Solution {\n public int minChanges(int n, int k) {\n if ((n & k) != k)\n return -1;\n return Integer.bitCount(n ^ k);\n }\n}\n```\n```Scala []\nobject Solution {\n def minChanges(n: Int, k: Int): Int = {\n if ((n & k) != k) {\n -1\n } else {\n Integer.bitCount(n ^ k)\n }\n }\n}\n```\n```Rust []\nimpl Solution {\n pub fn min_changes(n: i32, k: i32) -> i32 {\n if (n & k) != k {\n return -1;\n }\n (n ^ k).count_ones() as _\n }\n}\n```
| 3 | 0 |
['Math', 'Bit Manipulation', 'Python', 'Java', 'Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
✅ 0(1) Efficient Solution
|
01-efficient-solution-by-eleev-7yby
|
Code\nswift\nstruct Solution {\n @_optimize(speed)\n func minChanges(_ n: Int, _ k: Int) -> Int {\n k & ~n == 0 ? n.nonzeroBitCount - k.nonzeroBitC
|
eleev
|
NORMAL
|
2024-07-22T14:53:56.081485+00:00
|
2024-07-22T14:53:56.081520+00:00
| 17 | false |
# Code\n```swift\nstruct Solution {\n @_optimize(speed)\n func minChanges(_ n: Int, _ k: Int) -> Int {\n k & ~n == 0 ? n.nonzeroBitCount - k.nonzeroBitCount : -1\n }\n}\n```
| 3 | 0 |
['Bit Manipulation', 'Swift']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Simple beginer friendly Bit Manipulation approch
|
simple-beginer-friendly-bit-manipulation-4m16
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
rajan087
|
NORMAL
|
2024-07-21T04:07:35.439230+00:00
|
2024-07-21T04:07:35.439262+00:00
| 219 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int changes = 0;\n \n for (int i = 0; i < 31; ++i) {\n int bitN = n & (1 << i);\n int bitK = k & (1 << i);\n \n if (bitK == 0 && bitN != 0) {\n n ^= (1 << i);\n changes++;\n }\n }\n \n return (n == k) ? changes : -1;\n }\n};\n\n```
| 3 | 0 |
['Bit Manipulation', 'C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
💯Faster✅💯Less Mem✅🧠Detailed Approach🎯Bitwise Operation🔥C++😎
|
fasterless-memdetailed-approachbitwise-o-j9k6
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
swarajkr
|
NORMAL
|
2024-07-21T04:01:06.435049+00:00
|
2024-07-21T04:01:06.435082+00:00
| 98 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n bitset<32> a(n);\n bitset<32> b(k);\n\n int c = 0;\n\n for (int i = 0; i < 32; i++) {\n if (a[i] != b[i]) {\n c++;\n a[i] = 0;\n }\n }\n\n if(a == b){\n return c;\n }\n return -1;\n }\n};\n\n```
| 3 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
[JAVA] beats 100% user in java
|
java-beats-100-user-in-java-by-shubhash_-t1v4
|
\n\n# Approach\nbit masking and bit shifting\n# Complexity\n- Time complexity: O(31)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n A
|
Shubhash_Singh
|
NORMAL
|
2024-09-29T17:33:18.734034+00:00
|
2024-09-29T17:33:18.734076+00:00
| 85 | false |
\n\n# Approach\nbit masking and bit shifting\n# Complexity\n- Time complexity: O(31)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minChanges(int n, int k) {\n int c = 0;\n for(int i=0;i<31;i++){\n int mask = (1 << i);\n\n int b1 = n & mask;\n int b2 = k & mask;\n\n if ( b2 == 0 && b1 !=0){\n n = n^mask;\n c++;\n }\n }\n return (n == k ? c: -1);\n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
C# Think XOR beats 80% runtime
|
c-think-xor-beats-80-runtime-by-yash_shu-cawb
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThink XOR\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity
|
yash_shukla
|
NORMAL
|
2024-07-26T05:49:44.619424+00:00
|
2024-07-26T05:49:44.619456+00:00
| 24 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThink XOR\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(log(n))$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\npublic class Solution {\n public int MinChanges(int n, int k) {\n int count = 0;\n while( n > 0 || k > 0)\n {\n // Fetch last bit of the number\n int nBit = n & 1;\n int kBit = k & 1;\n\n // case1: if both the bits are same, xor will give the result as 0\n // case2: if both the bits are different, xor will give result as 1\n // case 2.1: if the nth is 1, we can safely turn it into 0\n // case 2.2: if the kth bit is 1, then we cannot change the bit from 1 to 0 hence return -1\n\n int xor = nBit ^ kBit;\n if(xor == 1 && kBit == 1) return -1;\n if(xor == 1) count ++;\n\n // right shift the bit by 1 (division operation)\n n >>= 1;\n k >>= 1;\n }\n\n return count;\n }\n}\n```
| 2 | 0 |
['C#']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
✅✅BEST AND SIMPLE SOLUTION🤩🤩
|
best-and-simple-solution-by-rishu_raj593-b9b4
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Rishu_Raj5938
|
NORMAL
|
2024-07-22T17:10:05.390427+00:00
|
2024-07-22T17:10:05.390498+00:00
| 20 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n \n int cnt = 0;\n \n for(int i=0; i<30; i++) {\n if(k & (1<<i)) {\n if(!(n&(1<<i))) {\n return -1;\n }\n }\n else {\n if(n&(1<<i)) cnt++;\n }\n }\n \n return cnt;\n }\n};\n```
| 2 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
✅ One Line Solution
|
one-line-solution-by-mikposp-olan
|
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1.1 - One Line\nTime complexity: O(1). S
|
MikPosp
|
NORMAL
|
2024-07-21T13:12:21.136476+00:00
|
2024-07-21T13:21:57.379790+00:00
| 66 | false |
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1.1 - One Line\nTime complexity: $$O(1)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n return max(-1,sum(v!=u and (1,-inf)[v==\'0\'] for v,u in zip_longest(bin(n)[:1:-1],bin(k)[:1:-1],fillvalue=\'0\')))\n```\n\n# Code #1.2 - Unwrapped\n```\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n res = 0\n for v,u in zip_longest(bin(n)[:1:-1], bin(k)[:1:-1], fillvalue=\'0\'):\n if v != u:\n if v == \'0\':\n return -1\n \n res += 1\n \n return res\n```\n\n(Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be \'true\' oneliners - please, remind about drawbacks only if you know how to make it better)
| 2 | 0 |
['Bit Manipulation', 'Python', 'Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Simple C++ Solution ✅✅
|
simple-c-solution-by-abhi242-24td
|
Code\n\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int use=n&k;\n if(use!=k){\n return -1;\n }\n int
|
Abhi242
|
NORMAL
|
2024-07-21T09:50:26.781101+00:00
|
2024-07-21T09:50:26.781124+00:00
| 53 | false |
# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int use=n&k;\n if(use!=k){\n return -1;\n }\n int temp=n^use;\n int ans=0;\n while(temp>0){\n if(temp%2==1){\n ans++;\n }\n temp=temp/2;\n }\n return ans;\n }\n};\n```
| 2 | 0 |
['Bit Manipulation', 'C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
XOR Method
|
xor-method-by-geramera-ptzc
|
Intuition\nThought of using bitwise operations to convert n and k to binary.\n\n# Approach\nHad to check if (n|k) == n. If the condition fails, return -1.\n\n#
|
geramera
|
NORMAL
|
2024-07-21T05:27:49.792974+00:00
|
2024-07-21T05:27:49.793007+00:00
| 32 | false |
# Intuition\nThought of using bitwise operations to convert n and k to binary.\n\n# Approach\nHad to check if (n|k) == n. If the condition fails, return -1.\n\n# Complexity\n- Time complexity:\nUsed XOR ( ^ )\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n \n def minChanges(self, n, k):\n if (n|k) !=n: \n return -1 \n \n diff = n^k \n return bin(diff).count(\'1\')\n```
| 2 | 0 |
['Python']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
🚀 Fastest Bit Manipulation: Transform Numbers in Just 3 Lines! 🔥✨
|
fastest-bit-manipulation-transform-numbe-dm4z
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThis approach identifies which bits differ between the numbers and checks if combining
|
01DP
|
NORMAL
|
2024-07-21T05:27:38.342448+00:00
|
2024-07-21T05:27:38.342472+00:00
| 242 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis approach identifies which bits differ between the numbers and checks if combining these differences with the target number recreates the original number.\n\n# Approach\nThis solution finds the minimum changes needed to transform one number into another using three steps:\n\n1. **Identify Differences:** It first finds which bits (binary digits) differ between the two numbers.\n2. **Combine Bits:** Then, it combines these differences with the target number to see if the original number can be recreated.\n3. **Count Changes:** Finally, if the numbers match, it counts the number of changes needed; if they don\'t match, it returns -1.\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int a = n ^ k;\n int b = k | a;\n return (b == n) ? __builtin_popcount(a) : - 1;\n }\n};\n```
| 2 | 0 |
['C++']
| 2 |
number-of-bit-changes-to-make-two-integers-equal
|
✨🚀 Effortlessly 💯 Dominate 100% with Beginner C++ , Java and Python Solution! 🚀✨
|
effortlessly-dominate-100-with-beginner-xl0ng
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Ravi_Prakash_Maurya
|
NORMAL
|
2024-07-21T04:08:48.424236+00:00
|
2024-07-21T04:08:48.424264+00:00
| 163 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n if (n == k) return 0;\n bitset<32> a = n, b = k;\n for (int i = 0; i < 32; ++i) if (b[i] && !a[i]) return -1;\n int x = 0;\n for (int i = 0; i < 32; ++i) if (a[i] && !b[i]) x++;\n return x;\n }\n};\n```\n```Java []\npublic class Solution {\n public int minChanges(int n, int k) {\n if (n == k) return 0;\n String a = String.format("%32s", Integer.toBinaryString(n)).replace(\' \', \'0\');\n String b = String.format("%32s", Integer.toBinaryString(k)).replace(\' \', \'0\');\n for (int i = 0; i < 32; ++i) {\n if (b.charAt(i) == \'1\' && a.charAt(i) == \'0\') return -1;\n }\n int x = 0;\n for (int i = 0; i < 32; ++i) {\n if (a.charAt(i) == \'1\' && b.charAt(i) == \'0\') x++;\n }\n return x;\n }\n}\n```\n```Python []\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n if n == k:\n return 0\n a = bin(n)[2:].zfill(32)\n b = bin(k)[2:].zfill(32)\n if any(b[i] == \'1\' and a[i] == \'0\' for i in range(32)):\n return -1\n x = sum(a[i] == \'1\' and b[i] == \'0\' for i in range(32))\n return x\n```\n
| 2 | 1 |
['C++', 'Java', 'Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
✅ Java Solution
|
java-solution-by-harsh__005-f7k0
|
CODE\nJava []\npublic int minChanges(int n, int k) {\n\tString bn = Integer.toBinaryString(n);\n\tString bk = Integer.toBinaryString(k);\n\n\tif(bn.length() < b
|
Harsh__005
|
NORMAL
|
2024-07-21T04:06:25.721439+00:00
|
2024-07-21T04:06:25.721469+00:00
| 368 | false |
## **CODE**\n```Java []\npublic int minChanges(int n, int k) {\n\tString bn = Integer.toBinaryString(n);\n\tString bk = Integer.toBinaryString(k);\n\n\tif(bn.length() < bk.length()) {\n\t\treturn -1;\n\t}\n\tint i = bn.length()-1, j = bk.length()-1, ct = 0;\n\twhile(i>=0 && j>=0) {\n\t\tchar ch1 =bn.charAt(i--), ch2 = bk.charAt(j--);\n\t\tif(ch1 != ch2) {\n\t\t\tif(ch1 == \'1\') ct++;\n\t\t\telse return -1;\n\t\t}\n\t}\n\n\twhile(i>=0) ct+=(bn.charAt(i--)==\'1\'? 1: 0);\n\n\treturn ct;\n}\n```
| 2 | 0 |
['Java']
| 1 |
number-of-bit-changes-to-make-two-integers-equal
|
✅Easy and simple solution ✅Explanation ✅Brute froce approach ✅clean code
|
easy-and-simple-solution-explanation-bru-vd37
|
Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F\nFoll
|
ayushluthra62
|
NORMAL
|
2024-07-21T04:00:41.026143+00:00
|
2024-07-21T04:00:41.026204+00:00
| 206 | false |
***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]**\n\n\n# Approach / Pseudo code\n1. we will find the bits of both n and k and store it in tempraory vector\n2. we will add zeros at the start so they both have same size \n3. now check if they have same bit or not \n4. if not check temp1[currbit] ==1 then we can convert it 0 otherwise return -1 because we can\'t make 0 to 1 \n5. else increment count\n6. return count\n\n\n# Complexity\n- Time complexity:\nO(Max(N,K)) \n\n- Space complexity:\nO(Max(N,K)) \n# Code\n```\nclass Solution {\npublic: \n\n // storing bit in tempraory vector \n void solve(vector<int>& temp,int n){\n while(n>0){\n temp.push_back(n%2);\n n=n/2;\n }\n reverse(temp.begin(),temp.end());\n }\n int minChanges(int n, int k) {\n if(n==k) return 0;\n \n vector<int>temp1,temp2;\n \n solve(temp1,n);\n solve(temp2,k);\n \n // adding zeros in front of temp2\n if(temp1.size() > temp2.size()){\n int j = temp2.size();\n reverse(temp2.begin(),temp2.end());\n while(j<temp1.size()) {\n temp2.push_back(0);\n j++;\n }\n reverse(temp2.begin(),temp2.end());\n }\n\n // adding zeros in front of temp1 \n if(temp2.size()>temp1.size()){\n int j = temp1.size();\n reverse(temp1.begin(),temp1.end());\n while(j<temp2.size()) {\n temp1.push_back(0);\n j++;\n }\n reverse(temp1.begin(),temp1.end());\n }\n \n \n \n \n int count =0;\n for(int i=0;i<temp1.size();i++){\n if(temp1[i] != temp2[i] ){\n if(temp1[i]==0) return -1;\n else count++;\n } \n }\n return count;\n \n }\n};\n```\n***Guy\'s if you find this solution helpful \uD83D\uDE0A, PLEASE do UPVOTE. By doing that it motivate\'s me to create more better post like this \u270D\uFE0F***<br>\n**Follow me on LinkeDin [[click Here](https://www.linkedin.com/in/ayushluthra62/)]**\n
| 2 | 0 |
['Array', 'C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Bitmask | C, C++, Python3
|
bitmask-c-c-python3-by-squirtleherder-xuk5
|
CC++Python3
|
SquirtleHerder
|
NORMAL
|
2025-02-07T20:36:28.086004+00:00
|
2025-02-07T20:36:28.086004+00:00
| 59 | false |
# C
```c []
int minChanges(int n, int k) {
if(k & ~n) return -1;
return __builtin_popcount((n & ~k));
}
```
# C++
```cpp []
class Solution {
public:
int minChanges(int n, int k) {
if(k & ~n) return -1;
return __builtin_popcount((n & ~k));
}
};
```
# Python3
```python3 []
class Solution:
def minChanges(self, n: int, k: int) -> int:
if k & ~n:
return -1
return (n & ~k).bit_count()
```
| 1 | 0 |
['Bit Manipulation', 'C', 'Bitmask', 'C++', 'Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
0ms C++ | Bit shift operator, straightforward logic
|
0ms-c-bit-shift-operator-straightforward-mlf9
|
Intuition & ApproachIf n is greater than k we may be able do bit changes (1 to 0) to get k. So we compare the bits of both numbers and run a counter c.Complexit
|
amithm7
|
NORMAL
|
2025-01-21T10:39:08.220919+00:00
|
2025-01-21T10:39:08.220919+00:00
| 41 | false |
# Intuition & Approach
If `n` is greater than `k` we may be able do bit changes (1 to 0) to get `k`. So we compare the bits of both numbers and run a counter `c`.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minChanges(int n, int k) {
if (n == k)
return 0;
if (k > n)
return -1;
int c = 0, b = 0;
// Checking bits from the right
while (b < 32) {
if (((n >> b) & 1) == 1 && ((k >> b) & 1) == 0)
c++;
else if (((n >> b) & 1) == 0 && ((k >> b) & 1) == 1)
return -1;
b++;
}
return c;
}
};
```
| 1 | 0 |
['Bit Manipulation', 'C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
☑️ Finding Number of Bit Changes to Make Two Integers Equal ☑️
|
finding-number-of-bit-changes-to-make-tw-kti3
|
Code
|
Abdusalom_16
|
NORMAL
|
2025-01-18T05:07:19.011652+00:00
|
2025-01-18T05:07:19.011652+00:00
| 18 | false |
# Code
```dart []
class Solution {
int minChanges(int n, int k) {
List<String> list = n.toRadixString(2).split("");
String conv2 = k.toRadixString(2).padLeft(list.length, '0');
int count = 0;
if(list.join() == conv2){
return count;
}
for(int i = 0; i < list.length; i++){
if(conv2[i] != list[i] && list[i] == "1" && conv2[i] == "0"){
list[i] = "0";
count++;
if(list.join() == conv2){
return count;
}
}
}
return -1;
}
}
```
| 1 | 0 |
['Bit Manipulation', 'Dart']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
C++ Super-Easy and Clean Solution, 0 ms Beats 100%
|
c-super-easy-and-clean-solution-0-ms-bea-n2mq
|
Code\ncpp []\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int res = 0;\n while (n) {\n if (n % 2 != k % 2) {\n
|
yehudisk
|
NORMAL
|
2024-11-21T13:01:41.468652+00:00
|
2024-11-21T13:01:41.468693+00:00
| 14 | false |
# Code\n```cpp []\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int res = 0;\n while (n) {\n if (n % 2 != k % 2) {\n if (n % 2) res++;\n else return -1;\n }\n n /= 2;\n k /= 2;\n }\n return k ? -1 : res; \n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
simple solution -> python , TC - log(n), SC - O(1)
|
simple-solution-python-tc-logn-sc-o1-by-w1h60
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
deepaliarpitagarwal
|
NORMAL
|
2024-09-21T07:07:59.534682+00:00
|
2024-09-21T07:07:59.534704+00:00
| 41 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n if n|k != n:\n return -1\n count = 0\n while n>0:\n if (n&1) == 1 and (k &1) ==0:\n count += 1\n n = n >> 1\n k = k >> 1\n return count\n```
| 1 | 0 |
['Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Easy to Understand , Bits 100% 💪
|
easy-to-understand-bits-100-by-waywidn-cqvh
|
Intuition\n\n\nLet\u2019s dive into solving this problem with a clear and engaging explanation!\n\n## Problem Description\n\nYou\u2019re given two positive inte
|
WAYWIDN
|
NORMAL
|
2024-09-11T17:27:04.325502+00:00
|
2024-09-11T17:27:04.325528+00:00
| 4 | false |
# Intuition\n\n\nLet\u2019s dive into solving this problem with a clear and engaging explanation!\n\n## Problem Description\n\nYou\u2019re given two positive integers, `n` and `k`. The goal is to transform `n` into `k` by flipping some of the `1s` in `n` to `0`s. Your task is to determine how many changes are needed, or return `-1` if it\u2019s impossible to make `n` equal to `k` by only changing `1s` in `n` to `0`s.\n\n## Approach\n\n1. **Identify Necessary Changes :**\n - To determine how many bit changes are needed, you need to compare the binary representations of `n` and `k`. Specifically, you need to determine which bits in `n` need to be flipped to match `k`.\n\n2. **Calculate Differences :**\n - Use XOR to find the bit positions where `n` and `k` differ. This is because XOR (`^`) will give you a result where each bit set to `1` represents a position where `n` and `k` have different bits.\n\n3. **Check Feasibility and Count Changes :**\n - For each bit position that is different (i.e., where XOR result is `1`):\n - **If `n` has a `0` at this position and `k` has a `1`**,mean you cannot make `n` equal to `k` by flipping only `1s` bit of `n`\n - **If `n` has a `1` at this position and `k` has a `0`**,mean you need to flip this `1` to `0`. Count these necessary flips.\n\n4. **Return the Result :**\n - After processing all bit positions, return the count of flips needed. If an impossible situation is encountered, return `-1`.\n\n## Detailed Approach\n\n1. **Compute XOR :**\n - Compute the XOR of `n` and `k`. The result, `_xor = n ^ k`, highlights the bits where `n` and `k` differ.\n\n2. **Count Flips :**\n - Initialize `count` to `0`.\n - Iterate through each bit of `_xor`:\n - If `_xor & 1` (i.e., the bit in XOR result is `1`):\n - **Check the corresponding bits in `n` and `k`:**\n - **If `n` has `0` and `k` has `1`** at this position, return `-1` because it\u2019s impossible to flip bits in `n` to achieve this.\n - **If `n` has `1` and `k` has `0`**, increment `count` because you need to flip this `1` in `n`.\n\n3. **Shift Bits :**\n - Right shift `n`, `k`, and `_xor` to process the next bit.\n\n4. **Return Result :**\n - Return the total count of flips.\n\nCertainly! Let\u2019s walk through another example to demonstrate the algorithm.\n\n## Complexity\n\n- **Time Complexity :** O(32) \n \n- **Space Complexity :** O(1)\n\n# Code\n```cpp []\nclass Solution\n{\npublic:\n int minChanges(int n, int k)\n {\n if (n == k)\n return 0;\n\n int _xor = n ^ k;\n\n int count = 0;\n\n while (_xor)\n {\n if (!(n & 1) && (k & 1) && (_xor & 1))\n return -1;\n else if ((n & 1) && !(k & 1) && (_xor & 1))\n count++;\n\n n >>= 1;\n k >>= 1;\n _xor >>= 1;\n }\n\n return count;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
C++ Readable.
|
c-readable-by-reetisharma-32zm
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWe have to transform a number n into another number k with the following rules:\n\n You
|
reetisharma
|
NORMAL
|
2024-07-23T16:32:22.739274+00:00
|
2024-07-23T16:32:52.462417+00:00
| 65 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have to transform a number n into another number k with the following rules:\n\n* You can change a bit from 1 to 0.\n* You **cannot** change a bit from 0 to 1.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize a counter count to 0 to track the number of changes needed.\n2. Loop through each bit position from 0 to 31:\n * Check if the i-th bit of n is set (1) or not (0).\n * Check if the i-th bit of k is set (1) or not (0).\n3. Evaluate the bit positions:\n * If the i-th bit of n is not set and the i-th bit of k is set, return -1 (since 0 to 1 is not allowed).\n * If the i-th bit of n is set and the i-th bit of k is not-set, increment count by 1 (we need to change this bit from 1 to 0).\n * If both bits are the same, do nothing.\n4. Return the count after evaluating all bits.\n\n# Complexity\n- Time complexity: O(32) is constant time.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n//1 to 0 is allowed\n//0 to 1 is not allowed\n\n int minChanges(int n, int k) {\n int count = 0;\n for(int i=0; i<32; i++){\n\n bool isSetN = false, isSetK = false;\n \n //checking ith bit\n if((1<<i) & n) isSetN = true;\n if((1<<i) & k) isSetK = true;\n\n //if N has a bit not set i.e. 0 and K has that bit set i.e. 1\n //since 0 to 1 is not allowed, return -1;\n if(!isSetN && isSetK) return -1;\n else if(isSetN && !isSetK) count++;\n }\n return count;\n }\n};\n```
| 1 | 0 |
['Bit Manipulation', 'C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
USING STRING (JAVA SOLN.) ----- NOT USED BITS-----
|
using-string-java-soln-not-used-bits-by-frnhi
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
abir_themaity
|
NORMAL
|
2024-07-22T18:12:25.417719+00:00
|
2024-07-22T18:12:25.417744+00:00
| 12 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minChanges(int n, int k) {\n \n if(n==k)\n return 0;\n if(n<k)\n return -1;\n int c=0,i;\n String str1=Integer.toString(n,2);\n String str2=Integer.toString(k,2);\n int k1=Math.max(str1.length(),str2.length());\n int k2=Math.min(str1.length(),str2.length());\n i=k1-k2;\n int j=0;\n for(int l=0;l<i;l++){\n char ch=str1.charAt(l);\n if(ch==\'1\')\n c++;\n }\n for(;i<str1.length();i++){\n char ch=str1.charAt(i);\n char ch2=str2.charAt(j++);\n if(ch==\'1\'&&ch2==\'0\')\n c++;\n else if(ch==\'0\'&&ch2==\'1\')\n return -1;\n }\n return c;\n }\n}\n```
| 1 | 0 |
['String', 'Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
One Line Method - bitwise approach
|
one-line-method-bitwise-approach-by-char-oec7
|
\n\nvar minChanges = (n, k) =>\n ((n & k) === k) ? (n ^ k) .toString(2).replace(/0/g, \'\').length : -1;\n\n\n\n#### it\'s a challenge for you to explain how
|
charnavoki
|
NORMAL
|
2024-07-22T09:44:40.568446+00:00
|
2024-07-22T09:44:40.568509+00:00
| 22 | false |
\n```\nvar minChanges = (n, k) =>\n ((n & k) === k) ? (n ^ k) .toString(2).replace(/0/g, \'\').length : -1;\n\n```\n\n#### it\'s a challenge for you to explain how it works\n#### please upvote, you motivate me to solve problems in original ways
| 1 | 0 |
['JavaScript']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Simple Array Approach | Beats 100% in Time and Space
|
simple-array-approach-beats-100-in-time-czy6y
|
\n### Simple Array Approach | Beats 100% in Time and Space | Beginner Friendly & Easy to Understand\n\n\nclass Solution {\n public int minChanges(int n, int
|
M4n5iii
|
NORMAL
|
2024-07-21T12:38:25.401920+00:00
|
2024-07-22T08:09:07.698528+00:00
| 70 | false |
\n### Simple Array Approach | Beats 100% in Time and Space | Beginner Friendly & Easy to Understand\n\n```\nclass Solution {\n public int minChanges(int n, int k) { \n\t//If n cannot be converted into k\n if ( (n & k) != k){\n return -1;\n }\n int res = 0;\n\t\t//Convert values into char array\n char[] nA= Integer.toBinaryString(n).toCharArray();\n char[] kA= Integer.toBinaryString(k).toCharArray();\n\t\t\n int nl = nA.length-1;\n int kl = kA.length-1;\n\t\t\n\t\t//Condition covering scenarios where nA and kA both have value in char array\n while(nl>=0 && kl>=0){\n if(nA[nl]!=kA[kl]){\n res++;\n }\n nl--;\n kl--;\n }\n\t\t//Condition when k array is exhauted, but n has some elements left\n while(nl>=0){\n if(nA[nl]==\'1\'){\n res++;\n }\n nl--;\n }\n return res;\n }\n}\n\n```
| 1 | 0 |
['Array', 'Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
String & Array Logic | Beats 100% in Time and Space |
|
string-array-logic-beats-100-in-time-and-3i9p
|
Tried to make it begineer friendly by only using bitwise AND for the base case, rest is all using Strings and Arrays.\n\n\n\nclass Solution {\n public int mi
|
Ash990
|
NORMAL
|
2024-07-21T12:30:55.217765+00:00
|
2024-07-21T12:30:55.217787+00:00
| 36 | false |
Tried to make it begineer friendly by **only using bitwise AND for the base case**, rest is all using Strings and Arrays.\n\n\n```\nclass Solution {\n public int minChanges(int n, int k) { \n \n\t\t// Base case if we are unable to convert N into K\n if ((n & k) != k){\n return -1;\n }\n \n String binaryN = Integer.toBinaryString(n);\n String binaryK = Integer.toBinaryString(k);\n \n int maxLength = Math.max(binaryN.length(), binaryK.length());\n\n\t\t// If length of binary K is less than N, add preceeding 0s to make them equal.\n while (binaryK.length() < maxLength) {\n binaryK = "0" + binaryK;\n }\n \n char[] nArray = binaryN.toCharArray();\n char[] kArray = binaryK.toCharArray();\n \n int count = 0;\n \n\t\t// Increase count whenever binary representation of N is 1 and K is 0\n for (int i = 0; i < nArray.length; i++) {\n if (nArray[i] != kArray[i] && nArray[i]==\'1\') {\n count++;\n }\n }\n return count;\n }\n}\n```
| 1 | 0 |
['Array', 'String', 'Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Easy to understand
|
easy-to-understand-by-manyaagargg-eefd
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
manyaagargg
|
NORMAL
|
2024-07-21T11:39:25.042905+00:00
|
2024-07-21T11:39:25.042933+00:00
| 32 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n if(n==k) return 0;\n int ans=0;\n while(n>0 && k>0){\n int x = n%2;\n int y = k%2;\n if(x==0 && y==1) return -1;\n if(x==1 && y==0) ans++;\n n=n/2;\n k=k/2;\n }\n while(n>0){\n int x= n%2;\n if(x==1) ans++;\n n=n/2;\n }\n while(k>0){\n int x = k%2;\n if( x==1) return -1;\n k=k/2;\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Beats 100%| Beginner Friendly | Easy Approach | Basic 🍟🧨
|
beats-100-beginner-friendly-easy-approac-98ck
|
Approach\n1)we find the binary representations of n and k.\n2)Any bit that is equal to 1 in n and equal to 0 in k needs to be changed.\n3)if there is a bit that
|
Tanmayi_Tadala
|
NORMAL
|
2024-07-21T11:10:17.684876+00:00
|
2024-07-21T11:10:17.684911+00:00
| 266 | false |
# Approach\n1)we find the binary representations of n and k.\n2)Any bit that is equal to 1 in n and equal to 0 in k needs to be changed.\n3)if there is a bit that is equal to 0 in n and equal to 1 in k --> return -1\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(1)\n# Python3\n\n```\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n if n==k:\n return 0\n nb=bin(n)[2:]\n kb=bin(k)[2:]\n if(len(nb)<len(kb)):\n diff=len(kb)-len(nb)\n nb=\'0\'*diff+nb\n if(len(kb)<len(nb)):\n diff=len(nb)-len(kb)\n kb=\'0\'*diff+kb\n count=0\n for i in range(len(nb)):\n if nb[i]==\'1\' and kb[i]==\'0\':\n count+=1\n if nb[i]==\'0\' and kb[i]==\'1\':\n return -1\n return count\n```\n# Java\n```\nclass Solution {\n public int minChanges(int n, int k) {\n String nb = Integer.toBinaryString(n);\n String kb = Integer.toBinaryString(k);\n if(n==k) return 0;\n int len1 = nb.length();\n int len2 = kb.length();\n if (len1 > len2) {\n kb = padWithZeros(kb, len1 - len2);\n } else if (len2 > len1) {\n nb = padWithZeros(nb, len2 - len1);\n }\n int count=0;\n for(int i=0;i<nb.length();i++){\n if(nb.charAt(i)==\'1\' && kb.charAt(i)==\'0\'){\n count++;\n }\n if(nb.charAt(i)==\'0\' && kb.charAt(i)==\'1\'){\n return -1;\n }\n }\n return count;\n }\n private String padWithZeros(String binary, int zerosToAdd) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < zerosToAdd; i++) {\n sb.append(\'0\');\n }\n sb.append(binary);\n return sb.toString();\n }\n}\n```
| 1 | 0 |
['Java', 'Python3']
| 1 |
number-of-bit-changes-to-make-two-integers-equal
|
Simple C++ soluion || Faster than 100% || TC: O(1)
|
simple-c-soluion-faster-than-100-tc-o1-b-0th4
|
Complexity\n- Time complexity: O(1)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
dhawalsingh564
|
NORMAL
|
2024-07-21T08:46:26.709845+00:00
|
2024-07-21T08:46:26.709888+00:00
| 45 | false |
# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int ans=0;\n for(int i=0;i<32;i++){\n if(n &(1<<i)){\n if(!(k & (1<<i))){\n ans++;\n }\n }\n else{\n if(k & (1<<i)){\n return -1;\n }\n }\n }\n return ans;\n }\n};\n```
| 1 | 0 |
['Bit Manipulation', 'C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
JAVA(Sol for Beginner)
|
javasol-for-beginner-by-kdhyani2000-x5p8
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Bitwise Operation Approach\n (2) String Conversion and Bit Compar
|
kdhyani2000
|
NORMAL
|
2024-07-21T05:13:07.843916+00:00
|
2024-07-21T05:13:07.843943+00:00
| 77 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n Bitwise Operation Approach\n <!-- (2) String Conversion and Bit Comparison Approach -->\n\n# Complexity\n- Time complexity:\n O(logn)\n <!-- (2) O(max(logn,logk)) -->\n\n\n# Code\n```\nclass Solution {\n public int minChanges(int n, int k) {\n if ((n | k) != n) {\n return -1;\n }\n int changes = 0;\n while (n > 0) {\n if ((n & 1) == 1 && (k & 1) == 0) {\n changes++;\n }\n n >>= 1;\n k >>= 1;\n }\n return changes;\n }\n}\n// (2)\n// public int minChanges(int n, int k) {\n// String binaryn = Integer.toBinaryString(n);\n// String binaryk = Integer.toBinaryString(k);\n\n// if (binaryk.length() > binaryn.length()) {\n// return -1;\n// }\n\n// int maxLength = Math.max(binaryn.length(), binaryk.length());\n// binaryn = String.format("%" + maxLength + "s", binaryn).replace(\' \', \'0\');\n// binaryk = String.format("%" + maxLength + "s", binaryk).replace(\' \', \'0\');\n\n// int changes = 0;\n// for (int i = 0; i < maxLength; i++) {\n// char bn = binaryn.charAt(i);\n// char bk = binaryk.charAt(i);\n\n// if (bk == \'1\' && bn == \'0\') {\n// return -1;\n// } else if (bn == \'1\' && bk == \'0\') {\n// changes++;\n// }\n// }\n\n// return changes;\n// }\n```
| 1 | 0 |
['Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Easy - Using bitset STL | Beats 100%
|
easy-using-bitset-stl-beats-100-by-durve-mss1
|
Approach\nCreate a bitset array for both the numbers that contains the binary representation of respective number.\n1. If a bit in n is 1 and a bit at same pos
|
durvesh_jazz
|
NORMAL
|
2024-07-21T04:43:16.189940+00:00
|
2024-07-21T04:44:24.350637+00:00
| 11 | false |
# Approach\nCreate a bitset array for both the numbers that contains the binary representation of respective number.\n1. If a bit in n is 1 and a bit at same pos in k is 0, definitely we can change 1 -> 0.\n2. If a bit in n is 0 and a bit at same pos in k is not zero, we return -1 immediately as 0 -> 1 can be performed therefore its impossible to form k from n.\n\n# Complexity\n- Time complexity:\nO(1) as loop runs for constant time of 32 iterations\n\n- Space complexity:\nO(1): each number is represented by 32 bits\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n if(n == k)\n return 0;\n\n bitset<32> n1(n);\n bitset<32> k1(k);\n int changes = 0;\n\n for(int i = 0; i < 32; i++){\n if(n1[i] == 1 && k1[i] == 0){\n changes++;\n }\n else if(n1[i] == 0 && k1[i] == 1){\n return -1;\n }\n }\n\n return changes;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Easy solution Python3 ✅
|
easy-solution-python3-by-mahendran930-3d7x
|
\n# Code\n\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n n_bits = []\n k_bits = []\n \n while n > 0:\n
|
mahendran930
|
NORMAL
|
2024-07-21T04:16:53.702609+00:00
|
2024-07-21T04:16:53.702634+00:00
| 96 | false |
\n# Code\n```\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n n_bits = []\n k_bits = []\n \n while n > 0:\n n_bits.append(str(n&1))\n n = n >> 1\n while k > 0:\n k_bits.append(str(k&1))\n k = k >> 1\n \n if len(k_bits) > len(n_bits):\n rem = len(k_bits) - len(n_bits)\n for i in range(rem):\n n_bits.append("0")\n elif len(k_bits) < len(n_bits):\n rem = len(n_bits) - len(k_bits)\n for i in range(rem):\n k_bits.append("0")\n n_bits = n_bits[::-1]\n k_bits = k_bits[::-1]\n \n Num_of_change = 0\n for i in range(len(k_bits)):\n if k_bits[i] == n_bits[i]:\n continue\n elif n_bits[i] == "1":\n n_bits[i] = \'0\'\n Num_of_change += 1\n elif n_bits[i] == "0":\n break\n return Num_of_change if n_bits == k_bits else -1\n \n```
| 1 | 0 |
['Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
[C++] Concise solution using bit manipulation
|
c-concise-solution-using-bit-manipulatio-fekg
|
Complexity\n- Time complexity: O(1)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
hth4nh
|
NORMAL
|
2024-07-21T04:16:14.839933+00:00
|
2024-07-21T04:16:14.839957+00:00
| 72 | false |
# Complexity\n- Time complexity: $$O(1)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` cpp []\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n if ((n & ~k) == (n ^ k)) return __builtin_popcount(n ^ k);\n return -1;\n }\n};\n```
| 1 | 0 |
['Bit Manipulation', 'C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
[JAVA] Explained Solution!
|
java-explained-solution-by-gaurav621-f2vo
|
convert integer to binary string.\n2. if len(binary(k)) > len(binary(n)) return -1, means we have more position as 1 in k for which n will be 0. EX: \n k = 1
|
gaurav621
|
NORMAL
|
2024-07-21T04:15:31.862042+00:00
|
2024-07-21T04:15:31.862071+00:00
| 4 | false |
1. convert integer to binary string.\n2. if len(binary(k)) > len(binary(n)) return -1, means we have more position as 1 in k for which n will be 0. EX: \n k = 10101\n n = 1000\n3. iterate on reverse of both strings to len of n, check if n ith position is 1 and k ith position is 0, if found, increase the result by 1 else return -1;\n4. for all remaining values in n, if ith position is 1, increase the result.\n\n\n\n# Code\n```\nclass Solution {\n public int minChanges(int n, int k) {\n int res = 0;\n String s1 = new StringBuilder(Integer.toBinaryString(n)).reverse().toString();\n String s2 = new StringBuilder(Integer.toBinaryString(k)).reverse().toString();\n if(s2.length() > s1.length()) return -1;\n for(int i = 0; i < s1.length(); i++) {\n if(i < s2.length()) {\n if(s2.charAt(i) != s1.charAt(i)) {\n if(s2.charAt(i) == \'1\') return -1;\n res++;\n }\n } else {\n if(s1.charAt(i) == \'1\') res++;\n }\n }\n return res;\n }\n}\n```
| 1 | 0 |
['Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Easy to UndertStand || Beginner Friendly
|
easy-to-undertstand-beginner-friendly-by-wi1f
|
Let\'s break down the solution for the problem at hand, covering the intuition, approach, complexity analysis, and the provided code.\n\n# Intuition\nThe proble
|
tinku_tries
|
NORMAL
|
2024-07-21T04:12:31.557558+00:00
|
2024-07-21T04:12:31.557588+00:00
| 48 | false |
Let\'s break down the solution for the problem at hand, covering the intuition, approach, complexity analysis, and the provided code.\n\n# Intuition\nThe problem involves finding the minimum number of bit changes required to transform an integer `n` into another integer `k`. The key is to compare the bits of `n` and `k` from the least significant bit to the most significant bit and count the changes needed.\n\n# Approach\n1. Initialize a counter `ans` to keep track of the number of bit changes.\n2. Iterate while `n` is not zero:\n - Check the least significant bit (LSB) of `n` and `k`.\n - If the LSB of `n` is 1 and the LSB of `k` is 0, increment the `ans` counter (as a change from 1 to 0 is needed).\n - If the LSB of `n` is 0 and the LSB of `k` is 1, return -1 (since changing a 0 bit to a 1 bit is not allowed in this problem).\n3. Right shift both `n` and `k` to process the next bit.\n4. If after processing all bits of `n`, `k` still has remaining bits with value 1, return -1 (as it\'s impossible to match `k`).\n5. Return the `ans` counter as the result.\n\n# Complexity\n- **Time complexity**: $$O(log n)$$, where $$log n$$ is the number of bits in the binary representation of `n`. This is because each iteration processes one bit.\n- **Space complexity**: $$O(1)$$, as only a few variables are used for computation and no additional data structures are required.\n\n# Code\n```cpp\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int ans = 0;\n while (n) {\n if (n % 2) { // If the current bit of n is 1\n if (k % 2 == 0) ans++; // If the current bit of k is 0, we need a change\n } else { // If the current bit of n is 0\n if (k % 2) return -1; // If the current bit of k is 1, it\'s impossible to change 0 to 1\n }\n n /= 2; // Right shift n to process the next bit\n k /= 2; // Right shift k to process the next bit\n }\n if (k > n) return -1; // If k still has bits left, it\'s impossible to match\n return ans;\n }\n};\n```\n\n### Explanation of the Code\n1. **Initialization**: `ans` is initialized to 0 to count the required changes.\n2. **Main Loop**:\n - The loop continues while `n` is not zero.\n - For each bit, if the bit of `n` is 1 and the bit of `k` is 0, increment `ans`.\n - If the bit of `n` is 0 and the bit of `k` is 1, return -1 because we cannot change a 0 to a 1.\n - Both `n` and `k` are right-shifted to process the next bit.\n3. **Post Loop Check**: \n - If `k` still has bits left after `n` is exhausted, return -1 as it\'s impossible to match `k`.\n4. **Return Result**: The count of changes (`ans`) is returned.
| 1 | 0 |
['Bit Manipulation', 'C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Simple to understand code bit operation!!
|
simple-to-understand-code-bit-operation-gj1kk
|
Here\'s the complete explanation for your solution to the problem where you need to determine the minimum number of changes required to convert the integer n to
|
ShreyasPathak11
|
NORMAL
|
2024-07-21T04:12:29.268698+00:00
|
2024-07-21T04:12:29.268718+00:00
| 43 | false |
Here\'s the complete explanation for your solution to the problem where you need to determine the minimum number of changes required to convert the integer `n` to `k` by changing bits from 1 to 0:\n\n### Intuition\nTo solve the problem, the key insight is that converting `n` to `k` is only possible if all bits set in `k` are either already set in `n` or can be ignored. This implies that the bits that are set in `k` but not in `n` would make it impossible to convert `n` to `k`.\n\n### Approach\n1. **Check Feasibility**: \n - First, check if `k` can be derived from `n` by verifying if all bits that are set in `k` are also set in `n`. This can be done using the bitwise AND operation between the complement of `n` and `k` (i.e., `k & ~n`). If the result is not zero, it means there are bits set in `k` that cannot be set in `n`, hence return `-1`.\n\n2. **Count Changes**: \n - If the conversion is feasible, compute the number of changes required by counting the number of bits that are set in the bitwise AND of `n` and the complement of `k` (i.e., `n & ~k`). These are the bits in `n` that need to be changed from 1 to 0 to match `k`.\n - Use a loop to count the number of set bits in `new` (which is `n & ~k`) and shift `new` right by one bit in each iteration until all bits are processed.\n\n### Complexity\n- **Time Complexity**: \n - The time complexity is \\(*O(log n)*\\) where \\(n\\) is the length of the binary representation of `n`. This is because the loop iterates through each bit of `new`.\n- **Space Complexity**: \n - The space complexity is \\(*O(1)*\\) since we are using a constant amount of space regardless of the input size.\n\n### Code\n```python\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n # Check if there are any bits in k that are not in n\n if k & ~n != 0:\n return -1\n \n # Count the number of bits to change from 1 to 0\n count = 0\n new = n & ~k\n while new:\n count += (new & 1)\n new >>= 1\n \n return count\n```\n
| 1 | 0 |
['Bit Manipulation', 'Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
O(1) SOLUTION BY ELDEN LORD
|
o1-solution-by-elden-lord-by-adityaarora-ka5d
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWE CHECK FOR EVERY BIT WHETHER WE CAN MAKE EQUAL OR NOT\nONE CASE WHEN WE CANT IS WHEN
|
adi_arr
|
NORMAL
|
2024-07-21T04:12:13.035170+00:00
|
2024-07-21T04:12:13.035211+00:00
| 11 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWE CHECK FOR EVERY BIT WHETHER WE CAN MAKE EQUAL OR NOT\nONE CASE WHEN WE CANT IS WHEN K==1 and n is not \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n ans=0\n \n for x in range(32):\n \n if n & 1 << x == 1<<x and k & 1<<x ==0:\n ans+=1\n elif n & 1 << x == 0 and k & 1<<x == 1<<x:\n return -1\n return ans \n \n```
| 1 | 0 |
['Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
C++ beginner friendly :
|
c-beginner-friendly-by-kartikeysingh907-7xbz
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nCheck if transformation is possible:\n\n- We use (n & k) != k to determin
|
kartikeysingh907
|
NORMAL
|
2024-07-21T04:03:50.211700+00:00
|
2024-07-21T04:03:50.211742+00:00
| 44 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n**Check if transformation is possible:**\n\n- We use (n & k) != k to determine if there is any bit in k that is 1 while the corresponding bit in n is 0. If this condition is true, then it is impossible to transform n into k using only the allowed bit changes, and we return -1.\n\n**Count the required changes:**\n\n- We initialize changes to 0 and then iterate through each bit of n and k.\n- For each bit position, we compare the least significant bits of n and k using (n & 1) and (k & 1).\n- If they differ, we increment changes.\n- We then right-shift both n and k to process the next bit.\n\n**Output the result:**\n\n- Finally, the function returns the total number of changes needed.\n\n\n# Code\n```\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n if ((n & k) != k) {\n return -1;\n }\n\n int changes = 0;\n while (n > 0) {\n \n if ((n & 1) != (k & 1)) {\n changes++;\n }\n \n n >>= 1;\n k >>= 1;\n }\n\n return changes;\n }\n};\n```
| 1 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Check each Bit | C++, Python, Java
|
check-each-bit-c-python-java-by-not_yl3-msly
|
Approach\n Describe your approach to solving the problem. \nIterate through all the bits in n. Dividing an integer by two is the same as shifting all the bits t
|
not_yl3
|
NORMAL
|
2024-07-21T04:03:17.545063+00:00
|
2024-07-21T14:38:18.493457+00:00
| 121 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nIterate through all the bits in `n`. Dividing an integer by two is the same as shifting all the bits to the right once, therefore we can use its parity (`n % 2`) for the value of the rightmost bit.\n\nSince we can only change ones in `n` to zeros, if a bit is zero in `n` but one in `k`, then we can return -1 from here. Otherwise, we increment `res` if the bit is a one in `n` and a zero in `k`.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int minChanges(int n, int k) {\n int res = 0;\n while (n || k){\n if (n % 2 == 0 && k % 2)\n return -1;\n else if (n % 2 != k % 2)\n res++;\n n /= 2;\n k /= 2;\n }\n return res;\n }\n};\n```\n```python []\nclass Solution:\n def minChanges(self, n: int, k: int) -> int:\n res = 0\n while n or k:\n if n % 2 == 0 and k % 2:\n return -1\n elif n % 2 != k % 2:\n res += 1\n n //= 2\n k //= 2\n return res\n```\n```Java []\nclass Solution {\n public int minChanges(int n, int k) {\n int res = 0;\n while (n != 0 || k != 0){\n if (n % 2 == 0 && k % 2 == 1)\n return -1;\n else if (n % 2 != k % 2)\n res++;\n n /= 2;\n k /= 2;\n }\n return res;\n }\n}\n```\n
| 1 | 0 |
['Bit Manipulation', 'C', 'Python', 'C++', 'Java', 'Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Java Solution using in-built method with Constant Time & Space ✅💯
|
java-solution-using-in-built-method-with-qp7n
|
Intuition1. Binary String Conversion:
We first convert both the integers n and k to their 32-bit binary representation. In Java, integers are typically represen
|
UnratedCoder
|
NORMAL
|
2025-04-09T06:07:32.960688+00:00
|
2025-04-09T06:07:32.960688+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
**1. Binary String Conversion:**
- We first convert both the integers n and k to their 32-bit binary representation. In Java, integers are typically represented with 32 bits.
- To ensure that both n and k are represented with exactly 32 bits, the following code is used:
- String s1 = String.format("%32s", Integer.toBinaryString(n)).replaceAll(" ", "0");
- String s2 = String.format("%32s", Integer.toBinaryString(k)).replaceAll(" ", "0");
- Integer.toBinaryString(n) converts the integer n to a binary string.
- String.format("%32s", ...) ensures the binary string is padded to 32 characters (if it's shorter).
- replaceAll(" ", "0") replaces any leading spaces with zeros, ensuring the string is exactly 32 characters long.
**2. Initial Count Setup:**
- A counter count is initialized to 0. This counter will track the number of bit flips (changes from 1 to 0 or 0 to 1) required to convert n to k.
**3. Iterating Over Each Bit:**
- The loop runs from i = 0 to i < 32 (since we're working with 32 bits).
- In each iteration, it compares the corresponding bits of n and k (i.e., s1.charAt(i) and s2.charAt(i)).
**4. Condition Checking:**
- If s1.charAt(i) == '0' && s2.charAt(i) == '1', this means that n has a 0 at this position, but k has a 1. In this case, it is impossible to convert n to k because we cannot turn a 0 into a 1 without additional constraints (e.g., using some operations like bitwise operations). So, the function returns -1 immediately to indicate an impossible transformation.
- If s1.charAt(i) == '1' && s2.charAt(i) == '0', it means that n has a 1 at this position, but k has a 0. This is a valid change because we can flip 1 to 0. The counter count is incremented to track this required bit flip.
**5. Returning the Result:**
- After the loop completes, the function returns the value of count, which represents the number of bit flips required to change n to k.
# Approach
<!-- Describe your approach to solving the problem. -->
**1. Binary String Conversion:**
- We first convert both the integers n and k to their 32-bit binary representation. In Java, integers are typically represented with 32 bits.
- To ensure that both n and k are represented with exactly 32 bits, the following code is used:
- String s1 = String.format("%32s", Integer.toBinaryString(n)).replaceAll(" ", "0");
- String s2 = String.format("%32s", Integer.toBinaryString(k)).replaceAll(" ", "0");
- Integer.toBinaryString(n) converts the integer n to a binary string.
- String.format("%32s", ...) ensures the binary string is padded to 32 characters (if it's shorter).
- replaceAll(" ", "0") replaces any leading spaces with zeros, ensuring the string is exactly 32 characters long.
**2. Initial Count Setup:**
- A counter count is initialized to 0. This counter will track the number of bit flips (changes from 1 to 0 or 0 to 1) required to convert n to k.
**3. Iterating Over Each Bit:**
- The loop runs from i = 0 to i < 32 (since we're working with 32 bits).
- In each iteration, it compares the corresponding bits of n and k (i.e., s1.charAt(i) and s2.charAt(i)).
**4. Condition Checking:**
- If s1.charAt(i) == '0' && s2.charAt(i) == '1', this means that n has a 0 at this position, but k has a 1. In this case, it is impossible to convert n to k because we cannot turn a 0 into a 1 without additional constraints (e.g., using some operations like bitwise operations). So, the function returns -1 immediately to indicate an impossible transformation.
- If s1.charAt(i) == '1' && s2.charAt(i) == '0', it means that n has a 1 at this position, but k has a 0. This is a valid change because we can flip 1 to 0. The counter count is incremented to track this required bit flip.
**5. Returning the Result:**
- After the loop completes, the function returns the value of count, which represents the number of bit flips required to change n to k.
# Complexity
- Time complexity: O(1)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(1)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class Solution {
public int minChanges(int n, int k) {
String s1 = String.format("%32s", Integer.toBinaryString(n)).replaceAll(" ", "0");
String s2 = String.format("%32s", Integer.toBinaryString(k)).replaceAll(" ", "0");
int count = 0;
for (int i = 0; i < 32; i++) {
if (s1.charAt(i) == '0' && s2.charAt(i) == '1') {
return -1;
} else if (s1.charAt(i) == '1' && s2.charAt(i) == '0') {
count++;
}
}
return count;
}
}
```
| 0 | 0 |
['Bit Manipulation', 'Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Bit manipulation | beats 100% | O(1)
|
bit-manipulation-beats-100-o1-by-kumarni-t4ev
|
IntuitionWe are given two integers n and k. We need to find the minimum number of bits to flip in n so that it becomes a superset of k in binary (i.e., all bits
|
kumarnis89
|
NORMAL
|
2025-04-07T20:05:36.648362+00:00
|
2025-04-07T20:05:36.648362+00:00
| 1 | false |
# Intuition
We are given two integers `n` and `k`. We need to find the **minimum number of bits to flip in `n`** so that it becomes a **superset of `k` in binary** (i.e., all bits that are set in `k` must also be set in `n`).
If `k` has a bit set that is not set in `n`, then it's **impossible** to transform `n` into such a number without setting that bit — and if we're only allowed to flip bits in `n`, not increase the length or use additional tricks, we should return -1 in that case.
# Approach
- First, check if `n` is a **bitwise superset** of `k` using `(n | k) == n`.
- If not, it's impossible to convert `n` to `k` by only flipping bits — return -1.
- If `n` is a superset of `k`, then count how many bits are **extra in `n`** that are not present in `k`.
- Use `Integer.bitCount(n)` to count how many bits are set in `n`.
- Use `Integer.bitCount(k)` to count how many bits are needed to be set in `k`.
- The difference is the number of **extra bits that should be turned off** in `n` to match `k`.
# Complexity
- Time complexity:
$$O(1)$$ — Bitwise operations and `Integer.bitCount` are constant time for fixed-width integers.
- Space complexity:
$$O(1)$$ — No extra space used.
# Code
```java
class Solution {
public int minChanges(int n, int k) {
if ((n | k) != n) return -1;
return Integer.bitCount(n) - Integer.bitCount(k);
}
}
| 0 | 0 |
['Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
C++ | Bit manipulation | Beats 100 %
|
c-bit-manipulation-beats-100-by-kena7-q0b7
|
Code
|
kenA7
|
NORMAL
|
2025-04-06T12:23:43.256782+00:00
|
2025-04-06T12:23:43.256782+00:00
| 2 | false |
# Code
```cpp []
class Solution {
public:
int minChanges(int n, int k)
{
int res=0;
for(int i=0;i<32;i++)
{
int nb=(n>>i)&1;
int kb=(k>>i)&1;
if(kb && !nb)
return -1;
res+=nb^kb;
}
return res;
}
};
```
| 0 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Beats 100% by time python short solution
|
beats-100-by-time-python-short-solution-4cwb7
|
Code
|
StikS32
|
NORMAL
|
2025-04-03T18:56:07.411167+00:00
|
2025-04-03T18:56:07.411167+00:00
| 1 | false |
# Code
```python3 []
class Solution:
def minChanges(self, n: int, k: int) -> int:
if n == k:
return 0
ans = 0
x = list(f'{n:020b}')
y = list(f'{k:020b}')
for i in range(20):
if x[i] == '1' and y[i] == '0':
x[i] = '0'
ans += 1
return ans if x == y else -1
```
| 0 | 0 |
['Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Simple Swift Solution
|
simple-swift-solution-by-felisviridis-5hrn
|
Code
|
Felisviridis
|
NORMAL
|
2025-04-01T15:11:18.678572+00:00
|
2025-04-01T15:11:18.678572+00:00
| 1 | false |

# Code
```swift []
class Solution {
func minChanges(_ n: Int, _ k: Int) -> Int {
if n < k { return -1 }
if n == k { return 0 }
var n = n, k = k, diff = 0
while n > 0 {
let nb = n % 2, kb = k % 2
if kb > nb {
return -1
} else if kb < nb {
diff += 1
}
n /= 2
k /= 2
}
return diff
}
}
```
| 0 | 0 |
['Swift']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
The easiest solution (beat 100%)
|
the-easiest-solution-beat-100-by-renatl1-yk1b
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
renatl14
|
NORMAL
|
2025-03-31T17:44:51.927080+00:00
|
2025-03-31T17:44:51.927080+00:00
| 1 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```golang []
func minChanges(n int, k int) int {
if k & (n-k) > 0{
return -1
}
ans := 0
n -= k
for n > 0{
now := n % 2
if now == 1{
ans += 1
}
n /= 2
}
return ans
}
```
| 0 | 0 |
['Bit Manipulation', 'Go']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Beats 100% || Single line solution || Bit Manipulation
|
beats-100-single-line-solution-bit-manip-ltdy
|
Code
|
jogesh06
|
NORMAL
|
2025-03-15T14:34:05.887376+00:00
|
2025-03-15T14:34:05.887376+00:00
| 3 | false |

# Code
```python3 []
class Solution:
def minChanges(self, n: int, k: int) -> int:
return -1 if k & ~n else (n & ~k).bit_count()
```
| 0 | 0 |
['Bit Manipulation', 'Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
C# easy , 0 ms Beats 100.00%
|
c-easy-0-ms-beats-10000-by-durbek_coder-rfvx
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
Durbek_Coder
|
NORMAL
|
2025-03-14T05:52:19.658038+00:00
|
2025-03-14T05:52:19.658038+00:00
| 2 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
public int MinChanges(int n, int k) {
if (n == k)
return 0;
// 2 lik sanoq tizimiga otkazish
string b = Convert.ToString(n, 2);
string c = Convert.ToString(k, 2);
// Uzunligi kichik bo'lgan stringni nol bilan to'ldiramiz
while (b.Length > c.Length)
c = "0" + c;
while (c.Length > b.Length)
b = "0" + b;
int j = 0, r = 0;
for (int i = 0; i < b.Length; i++) {
if (b[i] == '1' && c[i] == '0') {
j += 1;
}
if (b[i] == '0' && c[i] == '1') {
r += 1;
}
}
return (r == 0) ? j : -1;
}
}
```
| 0 | 0 |
['C#']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Compare bit by bit
|
compare-bit-by-bit-by-escaroda-glbu
| null |
escaroda
|
NORMAL
|
2025-03-13T13:30:23.617814+00:00
|
2025-03-13T13:30:23.617814+00:00
| 2 | false |
```golang []
func minChanges(n int, k int) int {
count := 0
for k > 0 || n > 0 {
bn := n & 1
bk := k & 1
n >>= 1
k >>= 1
if bn == bk {
continue
}
if bn == 0 {
return -1
}
count += 1
}
return count
}
```
| 0 | 0 |
['Bit Manipulation', 'Go']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
C++ | 3 different methods
|
c-o20-3-different-methods-by-serrabassao-4knk
|
1st solutionCreate bitset for both input numbers.
Individually check the value of each bit on both input numbers.
Whenever you find a togglable bit, deduce to t
|
serrabassaoriol
|
NORMAL
|
2025-03-12T20:48:12.330579+00:00
|
2025-03-12T20:50:44.053906+00:00
| 1 | false |
# 1st solution
Create bitset for both input numbers.
Individually check the value of each bit on both input numbers.
Whenever you find a togglable bit, deduce to the input number its corresponding bit value by using the adequate power of 2.
After iterating all the bits, check if both input numbers match.
Time complexity: O(2 * 20 + 1 * (20 + log(20))) = O(61) = O(1)
Space complexity: O(2 * 20) = O(40) = O(1)
```cpp []
#include <bitset>
#include <cstdint>
#include <cmath>
class Solution {
public:
int minChanges(int n, int k) {
const uint8_t maximum_bits_number = 20; // 10^6 < 2^20
const std::bitset<20> k_bitset = std::bitset<maximum_bits_number>(k);
std::bitset<20> n_bitset = std::bitset<maximum_bits_number>(n);
int8_t bits_changed = 0;
for (
uint8_t bit = 0;
bit < maximum_bits_number;
bit++
) {
if (n_bitset[bit] == 1 && k_bitset[bit] == 0) {
bits_changed++;
n -= std::pow(2, bit);
}
}
if (n != k) {
bits_changed = -1;
}
return bits_changed;
}
};
```
# 2nd solution
Improvement over 1st solution by not using additional space.
However, time complexity worsens since now in each bit iteration, we have to perform bit shift operations.
Time complexity: O(20 * (20 + 20 + log(20))) = O(826) = O(1)
Space complexity: O(1)
```cpp []
#include <bitset>
#include <cstdint>
#include <cmath>
class Solution {
public:
int minChanges(int n, int k) {
const uint8_t maximum_bits_number = 20; // 10^6 < 2^20
int8_t bits_changed = 0;
for (
uint8_t bit = 0;
bit < maximum_bits_number;
bit++
) {
if (
((n & (1 << bit)) != 0)
&& ((k & (1 << bit)) == 0)
) {
bits_changed++;
n -= std::pow(2, bit);
}
}
if (n != k) {
bits_changed = -1;
}
return bits_changed;
}
};
```
# 3rd solution
Solution which may be challenging to come by yourself.
Perform a bitwise XOR operation on both inputs.
Perform a bitwise AND operation on the result of the previous bitwise XOR operation and *n* input.
Check if the number of set bits in both bitwise operations match.
Time complexity: O(5 * 20) = O(100) = O(1)
- We can technically save a repeated std::popcount() call
Space complexity: O(1)
```cpp []
#include <bit>
#include <cstdint>
class Solution {
public:
int minChanges(int n, int k) {
const uint32_t xor_result = n ^ k;
const uint32_t and_result = n & xor_result;
int8_t bits_changed = std::popcount(xor_result);
if (std::popcount(xor_result) != std::popcount(and_result)) {
bits_changed = -1;
}
return bits_changed;
}
};
```
| 0 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
Easy to understand solution. Beats 100 %
|
easy-to-understand-solution-beats-100-by-cryu
|
ApproachThe condition if((n & k) != k) ensures that it’s possible to transform n into k. This works because the bitwise AND between n and k should yield k (i.e.
|
Khamdam
|
NORMAL
|
2025-03-09T07:49:53.047832+00:00
|
2025-03-09T07:49:53.047832+00:00
| 3 | false |
# Approach
The condition if((n & k) != k) ensures that it’s possible to transform n into k. This works because the bitwise AND between n and k should yield k (i.e., n must have all the 1s in k).
If n doesn’t have enough 1s in the positions where k requires them (i.e., n doesn't have all the 1s of k), we return -1 because it's impossible to transform.
If the transformation is possible, we count how many 1s are in n and k using Integer.bitCount(). The number of changes needed is the difference between the number of 1s in n and the number of 1s in k. This is because we can only turn 1s in n into 0s.
# Complexity
- Time complexity:
O(1)
- Space complexity:
O(1)
# Code
```java []
class Solution {
public int minChanges(int n, int k) {
if((n & k) != k) {
return -1;
}
return Integer.bitCount(n) - Integer.bitCount(k);
}
}
```
| 0 | 0 |
['Bit Manipulation', 'Java']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
number of bit changes to make two integers equal
|
number-of-bit-changes-to-make-two-intege-q6zk
|
Code
|
AnushaYelleti
|
NORMAL
|
2025-02-25T11:30:14.755309+00:00
|
2025-02-25T11:30:14.755309+00:00
| 4 | false |
# Code
```python3 []
class Solution:
def minChanges(self, n: int, k: int) -> int:
ml=max(len(format(n,'b')),len(format(k,'b')))
nb = format(n, f'0{ml}b')
kb=format(k,f'0{ml}b')
c=0
ans=""
for i in range(len(nb)):
if nb[i]=='1' and kb[i]=='0':
ans+='0'
c+=1
else:
ans+=nb[i]
if ans==kb:
return c
else:
return -1
```
| 0 | 0 |
['Python3']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
C++ Bit Manipulation
|
c-bit-manipulation-by-sy7794564-7y31
|
Code
|
sy7794564
|
NORMAL
|
2025-02-20T08:02:16.662662+00:00
|
2025-02-20T08:02:16.662662+00:00
| 5 | false |
# Code
```cpp []
class Solution {
public:
int minChanges(int n, int k) {
int c = n^k, ans = 0;
while (c > 0) {
if (c % 2) {
if (k % 2 == 0) {
ans++;
} else return -1;
}
c /= 2;
k /= 2;
}
return ans;
}
};
```
| 0 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
SIMPLE SOLUTION || USING BIT MANIPULATION || IN C++ || 100%
|
simple-solution-using-bit-manipulation-i-d0qk
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
sanjaykumar___
|
NORMAL
|
2025-02-18T17:27:06.831814+00:00
|
2025-02-18T17:27:06.831814+00:00
| 2 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minChanges(int n, int k) {
int a=n^k;
if(a==0){
return 0;
}
if(k>n){
return -1;
}
if((n&k) != k){
return -1;
}
int count=0;
while(a!=0){
count++;
a=a&(a-1);
}
return count;
}
};
```
| 0 | 0 |
['C++']
| 0 |
number-of-bit-changes-to-make-two-integers-equal
|
c++ easy approach
|
c-easy-approach-by-harshitasree-9ejz
|
IntuitionApproachComplexity
Time complexity:
Space complexity:
Code
|
harshitasree
|
NORMAL
|
2025-02-06T05:34:18.381228+00:00
|
2025-02-06T05:34:18.381228+00:00
| 6 | false |
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
int minChanges(int n, int k) {
int cnt = 0;
for(int i=0; i<30; i++) {
if(k & (1<<i)) {
if(!(n&(1<<i))) {
return -1;
}
}
else {
if(n&(1<<i)) cnt++;
}
}
return cnt;
}
};
```
| 0 | 0 |
['C++']
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.