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
number-complement
Short & Fast Java Solution (w/ Explanation)
short-fast-java-solution-w-explanation-b-dx98
Algorithm:\n\npublic int findComplement(int num) {\n\tint mask = -1;\n\twhile ((num & mask) != 0) {\n\t\tmask <<= 1;\n\t}\n\treturn ~num & ~mask; // Also equal
sidlak
NORMAL
2021-09-23T18:21:24.143137+00:00
2021-09-25T19:37:42.296684+00:00
822
false
**Algorithm:**\n```\npublic int findComplement(int num) {\n\tint mask = -1;\n\twhile ((num & mask) != 0) {\n\t\tmask <<= 1;\n\t}\n\treturn ~num & ~mask; // Also equal to ~(num ^ mask)\n}\n```\n**Explanation:**\nLets take this step by step. For the sake of my sanity, lets assume that integers are only 8-bits long. In our example, we will say that the bit representation of num is `00001101`.\n1. This sets mask to be an integer with ALL of its bits set to 1.\n\n\t```\n\tint mask = -1;\n\t```\n\tNote the current state of the variables:\n\t```\n\tnum: 00001101\n\tmask: 11111111\n\t```\n2. This while condition shifts the mask until it lines up with the leading zeroes in num. \n\t```\n\twhile ((num & mask) != 0) {\n\t\tmask <<= 1;\n\t}\n\t```\n\tNote that shifting the mask left will drop the first bit, and append a 0 to the end. (`11111111` shifted once would be `11111110`). Also, it is only once there are no more 1s in num that their bitwise-and would equal 0. Here is the state after this code is run:\n\t```\n\tnum: 00001101\n\tmask: 11110000\n\tnum & mask: 00000000\n\t```\n3. Finally, we need to invert the bits of num and only return the bits that were not part of the leading zeroes.\n\t```\n\treturn ~num & ~mask;\n\t```\n\tWe invert (flip 1s to 0s and vice versa) num because that is the thing we want to return. However, the leading zeroes need to be factored out, so we invert the mask and "cancel" out the leading zeroes. Note the following:\n\t```\n\t~num: 11110010\n\t~mask: 00001111\n\t~num & ~mask: 00000010\n\t```\nSo, we end up returning the correct value of `00000010`.\n\nLet me know if anything does not make sense!
9
0
['Bit Manipulation', 'Java']
1
number-complement
C++ Solution using XOR
c-solution-using-xor-by-nisargshah20-5t23
```\nclass Solution {\npublic:\n int findComplement(int num) {\n int count=0;\n int j=num;\n while(j!=0){\n j=j/2;\n
nisargshah20
NORMAL
2020-05-04T07:22:40.065490+00:00
2020-05-04T07:22:40.065541+00:00
1,182
false
```\nclass Solution {\npublic:\n int findComplement(int num) {\n int count=0;\n int j=num;\n while(j!=0){\n j=j/2;\n count++;\n }\n int ans = pow(2,count) - 1;\n return num ^ ans;\n }\n};\n
9
0
[]
1
number-complement
easy solution in java.
easy-solution-in-java-by-hilloni-tepy
public int findComplement(int num) {\n int x=1,i=1;\n while(x<=num && i<32)\n {\n num=num^x;\n x=x<<1;\n i+
hilloni
NORMAL
2018-08-15T13:07:00.802254+00:00
2018-08-22T22:38:54.392871+00:00
1,346
false
public int findComplement(int num) {\n int x=1,i=1;\n while(x<=num && i<32)\n {\n num=num^x;\n x=x<<1;\n i++;\n }\n \n return num;\n }
9
1
[]
1
number-complement
[C++] Brute-Force | 0ms | Worst Approach
c-brute-force-0ms-worst-approach-by-vaib-rqe9
\nclass Solution {\npublic:\n int findComplement(int num) {\n vector<int> val;\n while(num > 0){\n val.push_back(num % 2);\n
vaibhav4859
NORMAL
2021-12-27T12:34:21.045157+00:00
2021-12-27T12:34:21.045187+00:00
686
false
```\nclass Solution {\npublic:\n int findComplement(int num) {\n vector<int> val;\n while(num > 0){\n val.push_back(num % 2);\n num /= 2;\n }\n reverse(val.begin(), val.end());\n for(int i = 0; i < val.size(); i++)\n if(val[i] == 0) val[i] = 1;\n else val[i] = 0;\n \n int ans = 0;\n long int base = 1;\n for(int i = val.size()-1; i >= 0; i--){\n if(val[i] == 1) ans += val[i]*base;\n base *= 2;\n }\n return ans;\n }\n};\n```
8
0
['C', 'C++']
0
number-complement
✔️ [Python3] BITWISE OPERATORS •͡˘㇁•͡˘, Explained
python3-bitwise-operators-vv-explained-b-znjk
The idea is to shift all bits of the given integer to the right in the loop until it turns into 0. Every time we do a shift we use a mask to check what is in th
artod
NORMAL
2021-12-27T01:32:09.523438+00:00
2021-12-28T05:47:06.361854+00:00
1,205
false
The idea is to shift all bits of the given integer to the right in the loop until it turns into `0`. Every time we do a shift we use a mask to check what is in the right-most bit of the number. If bit is `0` we add `2**n` to the result where `n` is the current number of shifts. Example:\n```\nn=0, num=1010, bit=0 => res += 2**0\nn=1, num=0101, bit=1 => res += 0\nn=2, num=0010, bit=0 => res += 2**2\nn=3, num=0001, bit=1 => res += 0\n num=0000 => break the loop\n```\n\nRuntime: 24 ms, faster than **94.85%** of Python3 online submissions for Number Complement.\nMemory Usage: 14.2 MB, less than **68.47%** of Python3 online submissions for Number Complement.\n\n```\nclass Solution:\n def findComplement(self, num: int) -> int:\n res, n = 0, 0\n while num:\n if not num & 1:\n res += 2**n\n \n num >>= 1\n n += 1\n \n return res\n```
8
0
['Bit Manipulation', 'Python3']
1
number-complement
🔥%Multiple solutions 🎉||100%🔥Beats ✅
multiple-solutions-100beats-by-shivanshg-dxt4
Code\ncpp []\n\n// approch brute bruteeeeee forceeeee every student can doooo\nclass Solution {\npublic:\n string decimalTobinary(int n) {\n string s
ShivanshGoel1611
NORMAL
2024-08-22T11:24:35.895567+00:00
2024-08-22T11:24:35.895651+00:00
1,229
false
# Code\n```cpp []\n\n// approch brute bruteeeeee forceeeee every student can doooo\nclass Solution {\npublic:\n string decimalTobinary(int n) {\n string s = "";\n while (n) {\n s = s + to_string(n % 2);\n n = n / 2;\n }\n return s;\n }\n int binaryTodecimal(string s) {\n int n = s.size();\n int num = 0;\n for (int i = n - 1; i >= 0; i--) {\n num = num + (s[i] - \'0\') * pow(2, i);\n }\n return num;\n }\n int findComplement(int num) {\n string s = decimalTobinary(num);\n for (int i = 0; i < s.size(); i++) {\n (s[i] == \'1\') ? s[i] = \'0\' : s[i] = \'1\';\n }\n return binaryTodecimal(s);\n }\n};\n\n// approch 2 best and optimized space and time\n// class Solution {\n// public:\n// int findComplement(int num) {\n// int ans = 0;\n// int i = 0;\n// while (num) {\n// (num % 2 == 1) ?: ans += pow(2, i);\n// num /= 2;\n// i++;\n// }\n// return ans;\n// }\n// };\n// approch brute bruteeeeee forceeeee every student can doooo\n\n```
7
0
['Array', 'Bit Manipulation', 'Bitmask', 'Python', 'C++', 'Java', 'JavaScript']
0
number-complement
✅ One Line Solution
one-line-solution-by-mikposp-gf0g
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: O(1). Space complexi
MikPosp
NORMAL
2024-08-22T09:30:20.825645+00:00
2024-08-22T19:39:22.136636+00:00
813
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\nTime complexity: $$O(1)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def findComplement(self, v: int) -> int:\n return v^2**v.bit_length()-1\n```\n\n# Code #2\nTime complexity: $$O(1)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def findComplement(self, v: int) -> int:\n return v^(2<<int(log2(v)))-1\n```\nSeen [here](https://leetcode.com/problems/number-complement/solutions/96026/python-4-ways)\n\n# Code #3\nTime complexity: $$O(1)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def findComplement(self, v: int) -> int:\n return ~v+2**len(f\'{v:b}\')\n```\nSeen [here](https://leetcode.com/problems/number-complement/solutions/3896397/Python.-One-line-solution./comments/2586149)\n\n# Code #4\nTime complexity: $$O(1)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def findComplement(self, v: int) -> int:\n return v^int(\'1\'*v.bit_length(),2)\n```\n\n# Code #5\nTime complexity: $$O(1)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def findComplement(self, v: int) -> int:\n return int(re.sub(\'(.)\',lambda m:\'01\'[m[1]<\'1\'],f\'{v:b}\'),2)\n```\n\n# Code #6\nTime complexity: $$O(1)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def findComplement(self, v: int) -> int:\n return int(f\'{v:b}\'.replace(\'0\',\'.\').replace(\'1\',\'0\').replace(\'.\',\'1\'),2)\n```
7
0
['Bit Manipulation', 'Python', 'Python3']
0
number-complement
Swift | One-liner explained
swift-one-liner-explained-by-vladimirthe-ufx4
Approach\n~num inverts all bits in num\nFor example, 5 which is 00000000000000000000000000000|101 in binary, becomes 11111111111111111111111111111|010 \n\nTo ge
VladimirTheLeet
NORMAL
2024-08-22T00:55:57.931022+00:00
2024-08-22T01:30:58.218717+00:00
276
false
# Approach\n`~num` inverts all bits in `num`\nFor example, `5` which is `00000000000000000000000000000|101` in binary, becomes `11111111111111111111111111111|010` \n\nTo get rid of these leading `1`-s we first bitshift this number to the left by `num.leadingZeroBitCount` postions, getting `010|00000000000000000000000000000`, then back right by the same number, obtaining the desired result `00000000000000000000000000000|010`\n\n# Complexity\n- Time complexity: $O(1)$\n- Space complexity: $O(1)$\n\n# Code\n```swift []\nclass Solution {\n func findComplement(_ num: Int) -> Int {\n (~num << num.leadingZeroBitCount) >> num.leadingZeroBitCount\n }\n}\n```
7
0
['Bit Manipulation', 'Swift']
1
number-complement
Java | Beginner Friendly | Runtime: 1ms
java-beginner-friendly-runtime-1ms-by-sh-aq5q
\nclass Solution {\n public int findComplement(int num) {\n\t\tString binary = Integer.toBinaryString(num);\n\t\tString complement = "";\n\t\tfor(int i = 0;
shishir-kon
NORMAL
2021-12-27T03:50:07.145686+00:00
2021-12-27T06:00:21.173840+00:00
543
false
```\nclass Solution {\n public int findComplement(int num) {\n\t\tString binary = Integer.toBinaryString(num);\n\t\tString complement = "";\n\t\tfor(int i = 0; i < binary.length(); i++) {\n\t\t\tif(binary.charAt(i) == \'1\') {\n\t\t\t\tcomplement += \'0\';\n\t\t\t}\n\t\t\telse if(binary.charAt(i) == \'0\') {\n\t\t\t\tcomplement += \'1\';\n\t\t\t}\n\t\t}\n\t\tint decimal = Integer.parseInt(complement, 2); \n\t\treturn decimal; \n }\n}\n```
7
1
['Java']
0
number-complement
99.20% faster python MUCH easy solution.
9920-faster-python-much-easy-solution-by-roe5
\nclass Solution:\n def findComplement(self, num: int) -> int:\n complement=""\n for i in bin(num)[2:]:\n if i is "0":\n
jorjis
NORMAL
2021-05-11T20:22:55.619806+00:00
2021-05-11T20:22:55.619841+00:00
765
false
```\nclass Solution:\n def findComplement(self, num: int) -> int:\n complement=""\n for i in bin(num)[2:]:\n if i is "0":\n complement+="1"\n else:\n complement+="0"\n \n return int(complement,2)\n```
7
0
['Python', 'Python3']
2
number-complement
[C++, Python] 3 line with Explanation, Faster than 100%
c-python-3-line-with-explanation-faster-y6dc7
C++\n\nint findComplement(int num) {\n\tint k = int(log2(num));\n\tint mask = pow(2,k+1) - 1;\n\treturn num^mask;\n}\n\n#### Python3\n\ndef findComplement(self,
Vishruth_S
NORMAL
2021-01-16T14:22:16.008888+00:00
2021-01-17T05:13:16.007958+00:00
433
false
#### C++\n```\nint findComplement(int num) {\n\tint k = int(log2(num));\n\tint mask = pow(2,k+1) - 1;\n\treturn num^mask;\n}\n```\n#### Python3\n```\ndef findComplement(self, num: int) -> int:\n\tk = int(log2(num))\n\tmask = int(2**(k+1) - 1)\n\treturn num^mask;\n```\n#### Explanation\nWe want to flip every bit. One way to flip a bit is by taking its xor with 1. Because\n```\n0 xor 1 = 1\n1 xor 1 = 0\n```\n\n\nWith this in mind, all we have to do is take the XOR of all bits with 1.\nLet\'s say our number is 5 ,ie, 101\nso we need to take the xor with 111\nSince\n```\n1 0 1 xor\n1 1 1\n_________\n0 1 0 \n```\n\nHow to generate 111 ?\nAs you can observe, 111 is the number 7, which is 8 - 1, or 2^3 - 1.\nTo get the desired number with all bits as 1,\n\n1) Take the log of that number, say k (Eg: (```log2(5) = 2```))\n2) Take Power of ```2``` raised to ```k+1``` (2^3=8 or ```1000```) and subtract 1 (7 or ```111```)\n\n\n
7
0
['Bit Manipulation', 'C']
1
number-complement
C++ Solution EXPLAINED FULLY
c-solution-explained-fully-by-wa_magnet-qd8a
Approach : \n1. First we will find the number of bits in the given integer \n2. Then we will find the maximum number having same number of bits.(call it x )\n3
wa_magnet
NORMAL
2020-05-04T07:08:16.535429+00:00
2020-05-04T07:25:03.709453+00:00
382
false
Approach : \n1. First we will find the number of bits in the given integer \n2. Then we will find the maximum number having same number of bits.(call it x )\n3. Then we will XOR the given integer with x\n\nFor example : If input is 5 ,Binary Rep = 101 the number of bits = 3\n\t\t\t\t\tMax number , x = pow(2,number of bits) - 1 = pow(2,3) - 1 = 7\n\t\t\t\t\tBinary Rep of x = 111\n\t\t\t\t\tOur ans = XOR of ( given num and x ) = 101 XOR 111 = 010 = 2 (in decimal )\n\n\n\n\n```\n\n```public:\n int findComplement(int num) {\n if(num == 0)\n return 1 ;\n int p = log2(num)+ 1 ;\n int x = pow(2, p) - 1 ; \n return num ^ x ;\n }\n};\n```\nNote : log2(num) returns 1 less than total number of bits , so we add 1 .\n\nFeel free to comment :)
7
1
[]
1
number-complement
Straightforward Python
straightforward-python-by-awice-8o7x
This is not the shortest solution, but I believe straightforward solutions are more instructive.\n\nConsider the binary representation of the number.\nEvery 0 a
awice
NORMAL
2017-01-08T19:50:01.956000+00:00
2017-01-08T19:50:01.956000+00:00
1,263
false
This is not the shortest solution, but I believe straightforward solutions are more instructive.\n\nConsider the binary representation of the number.\nEvery 0 at the ith position from the right. adds 2**i to the result.\n\n```\ndef findComplement(self, N):\n binary = bin(N)[2:]\n ans = 0\n for i, u in enumerate(binary[::-1]):\n if u == '0':\n ans += 2 ** i\n return ans\n```
7
1
[]
0
number-complement
0 ms C++ code without xor or not.
0-ms-c-code-without-xor-or-not-by-bechon-qyta
Basic idea is to find the smallest power of 2 idx that is larger than the input number num, and output the difference between idx and num . For example, input 5
bechone
NORMAL
2017-03-31T00:34:54.327000+00:00
2017-03-31T00:34:54.327000+00:00
541
false
Basic idea is to find the smallest power of 2 `idx` that is larger than the input number `num`, and output the difference between `idx` and `num` . For example, input `5 (101)` , the smallest power of 2 (and larger than `5`) is `8 (1000)`, the output should be `8 - 5 - 1 = 2 (010)`. \n\n```\nclass Solution {\npublic:\n int findComplement(int num) {\n int idx = 2, tmp = num;\n \n while(tmp>>1) {\n tmp >>= 1;\n idx <<= 1;\n }\n \n return idx - num - 1;\n }\n};\n```
7
0
[]
0
number-complement
JavaScript solutions, bits and strings
javascript-solutions-bits-and-strings-by-9mfs
The bit version:\n\nvar findComplement = function(num) {\n let mask = 1;\n while (mask < num) mask = (mask << 1) | 1;\n return num ^ mask;\n};\n\nThe s
loctn
NORMAL
2017-05-06T18:23:52.227000+00:00
2017-05-06T18:23:52.227000+00:00
1,041
false
The bit version:\n```\nvar findComplement = function(num) {\n let mask = 1;\n while (mask < num) mask = (mask << 1) | 1;\n return num ^ mask;\n};\n```\nThe string version:\n```\nvar findComplement = function(num) {\n return parseInt(num.toString(2).split('').map(d => +!+d).join(''), 2);\n};\n```\nA combination of bits and strings that is fast:\n```\nvar findComplement = function(num) {\n return parseInt((~num ^ 1 << 31).toString(2).substr(-num.toString(2).length), 2);\n};\n```\nIn the last solution we negate the bits, including leading zeros, and get rid of the sign bit. Then we take the right side that we need which has the same number of digits as `num`.
7
0
['JavaScript']
3
number-complement
Start Flipping From The First Set Bit From Left To Right Direction | Java | C++ | [Video Solution]
start-flipping-from-the-first-set-bit-fr-rhid
Intuition, approach, and complexity discussed in detail in video solution.\nhttps://youtu.be/qmC8KKKZGp0\n# Code\njava []\nclass Solution {\n public int find
Lazy_Potato_
NORMAL
2024-08-22T05:17:35.157886+00:00
2024-08-22T05:17:35.157914+00:00
2,103
false
# Intuition, approach, and complexity discussed in detail in video solution.\nhttps://youtu.be/qmC8KKKZGp0\n# Code\n```java []\nclass Solution {\n public int findComplement(int num) {\n boolean setBitFound = false;\n for(int bitPos = 30; bitPos > -1; bitPos--){\n int mask = (1 << bitPos);\n if((num & mask) != 0){\n if(!setBitFound)setBitFound = true;\n }\n if(setBitFound){\n num ^= mask;\n }\n }\n return num;\n }\n}\n```\n```cpp []\nclass Solution {\npublic:\n int findComplement(int num) {\n bool setBitFound = false;\n for(int bitPos = 30; bitPos > -1; bitPos--){\n int mask = (1 << bitPos);\n if((num & mask) != 0){\n if(!setBitFound)setBitFound = true;\n }\n if(setBitFound){\n num ^= mask;\n }\n }\n return num;\n }\n};\n```
6
0
['Bit Manipulation', 'C++', 'Java']
2
number-complement
.::kotlin::. Bit mask with xor
kotlin-bit-mask-with-xor-by-dzmtr-ir0j
\nclass Solution {\n fun findComplement(num: Int): Int {\n var i = 0\n var t = num\n while (t > 0) {\n t = t shr 1\n
dzmtr
NORMAL
2024-06-15T12:18:12.278558+00:00
2024-06-15T12:18:12.278593+00:00
23
false
```\nclass Solution {\n fun findComplement(num: Int): Int {\n var i = 0\n var t = num\n while (t > 0) {\n t = t shr 1\n i++\n }\n val mask = (1 shl i) - 1 // -1 is the trick to make mask 1000 -> 111\n return num xor mask\n }\n}\n```
6
0
['Kotlin']
0
number-complement
476: Solution with step by step explanation
476-solution-with-step-by-step-explanati-pi1r
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Convert the given integer \'num\' to its binary string representation
Marlen09
NORMAL
2023-03-10T17:48:56.638241+00:00
2023-03-10T17:48:56.638280+00:00
2,423
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Convert the given integer \'num\' to its binary string representation using the built-in \'bin()\' function in Python.\n2. Flip all bits in the binary string obtained in step 1 to obtain the binary string representation of its complement. This can be done by iterating over each bit in the binary string and replacing each \'0\' with \'1\' and vice versa.\n3. Convert the binary string obtained in step 2 back to its decimal integer representation using the built-in \'int()\' function in Python with base 2.\n4. Return the integer obtained in step 3 as the result.\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 findComplement(self, num: int) -> int:\n # Convert num to binary string\n binary = bin(num)[2:]\n\n # Flip all bits in the binary string\n flipped_binary = \'\'.join([\'0\' if bit == \'1\' else \'1\' for bit in binary])\n\n # Convert the flipped binary string back to an integer\n if flipped_binary:\n return int(flipped_binary, 2)\n else:\n return 1\n\n```
6
0
['Bit Manipulation', 'Python', 'Python3']
0
number-complement
Java | easier bitmask solution
java-easier-bitmask-solution-by-prezes-8k4c
Upvote if you find this easier than the editorial.\n```\npublic int findComplement(int num) {\n\tint mask= 1;\n\twhile(num>mask) mask= (mask<<1) | 1;\n\treturn
prezes
NORMAL
2021-12-27T02:24:22.617408+00:00
2021-12-27T02:27:52.984100+00:00
442
false
Upvote if you find this easier than the editorial.\n```\npublic int findComplement(int num) {\n\tint mask= 1;\n\twhile(num>mask) mask= (mask<<1) | 1;\n\treturn num^mask;\n}
6
1
[]
1
number-complement
[C++] Simple Approaches (W/ Explanation) | Faster than 100%
c-simple-approaches-w-explanation-faster-nz9t
Brute Force Approach :\n\n The Brute force approach to solve the problem would be to first convert the given number into its binary representation and then flip
Mythri_Kaulwar
NORMAL
2021-12-27T01:58:23.613415+00:00
2021-12-27T02:03:28.044464+00:00
938
false
**Brute Force Approach :**\n\n* The Brute force approach to solve the problem would be to first convert the given number into its binary representation and then flip every bit in the binary representation. \n* After changing all 0\u2019s and 1\u2019s convert the binary representation to number.\n\nTime Complexity : O(n) - n = no. of bits in ```num```\n\nAuxiliary Space : O(n) \n\n**Code :**\n```\nclass Solution {\npublic:\n int findComplement(int num) {\n\t\tvector<int> v;\n\t\twhile (n != 0) { //convert the number to it\'s binary form & store the bits in "v"\n\t\t\tv.push_back(num%2);\n\t\t\tnum = num / 2;\n\t\t}\n\t\treverse(v.begin(), v.end());\n\t\tfor (int i = 0; i < v.size(); i++) v[i] = (v[i]==0) ? 1 : 0; //Flip the bits in the binary form\n\t\t// convert back to number representation\n\t\tint two = 1;\n\t\tfor (int i = v.size() - 1; i >= 0; i--) {\n\t\t\tnum = num + v[i] * two;\n\t\t\ttwo = two * 2;\n\t\t}\n return num;\n }\n};\n```\n\n**XOR Approach :**\n* The only operation that can reverse the bits of a number (say : ```101``` to ```010``` is XOR (```^```) operation. \n* So we need to XOR the given number with a number that has the same no. of bits & all bits set to 1 (here, ```111```).\n* **How to count the number of bits in the given number ?**\n1. Initialize 2 variables ```ans = 1``` & ```n = num```.\n2. Until n is <= 1, do ```n >>= 1``` (decrementing 1 bit in ```n```), ```ans <<= 1``` (incerementing 1 bit in ```ans```) and ```ans |= 1``` (Setting the last bit of ```ans```).\n\n* Now that we have obtained a number that has as many bits as the input, perform **XOR** between the 2 numbers to flip all the bits of the input number.\n\nTime Complexity : O(logn) (Each time we\'re doing n = n/2) - Where n = ```num```\n\nSpace Complexity : O(1) - No extra space used\n\n**Code :**\n```\nclass Solution {\npublic:\n int findComplement(int num) {\n int n = num, ans = 1;\n while(n != 1){\n n >>= 1;\n ans <<= 1;\n ans |= 1;\n }\n \n ans ^= num;\n \n return ans;\n }\n};\n```\n\nIf you like my solutions & explanation; please upvote :)\n\n\n\n
6
1
['Bit Manipulation', 'C', 'C++']
0
number-complement
[Python] Fastest One Liner (timed)
python-fastest-one-liner-timed-by-jeffwe-hf8c
Fastest Method Code\n\nclass Solution:\n def findComplement(self, num: int) -> int: \n return ~num + (1<<len(bin(num))-2)\n\n\n# Analysis\nThis
jeffwei
NORMAL
2020-05-05T05:35:28.319429+00:00
2020-05-23T13:06:56.035333+00:00
549
false
# Fastest Method Code\n```\nclass Solution:\n def findComplement(self, num: int) -> int: \n return ~num + (1<<len(bin(num))-2)\n```\n\n# Analysis\nThis line adds the complement of num (```~num```) with 2^n, where n = the number of bits in the binary representation of num. Let\'s take a look at why this works:\n\n## Brute Force Method\nThe straightforward method would be to convert ```num``` to a binary string, flip all the bits, and then convert that back to binary:\n```\nbinaryNum = bin(num)[2:]\nbinaryNumFlipped = \'\'\nfor i in binaryNum:\n\tbinaryNumFlipped += \'1\' if i == 0 else \'0\'\nreturn int(binaryNumFlipped, 2)\n```\n\n## Complement Method\nIn programming, the two\'s complement of a number (```~num```) is defined as ```-(num+1)```. So, the two\'s complement of 5 would be -6. The complement is with respect to 2^N\u2014that is, ```num + ~num = 2^N``` where N is the number of bits in our representation. In binary, this can be calculated by flipping all the bits and adding one. So if we convert 5 to binary, flip all the bits, and add them together, we should get 2^N-1.\n```\n 101 (5)\n+ 010 (2)\n ---\n 111 (7)\n+ 1 (1)\n ---\n 1000 (8)\n ```\n From this, we can easily see that in order to find the complement of 5, we simply need to use the formula ```2^N - 1 - num```, where N = the number of bits in 5 (in this case, 3). In code:\n ```\n 2**(len(bin(num))-2) - 1 - num\n ```\n*Note that since Python uses the ```\'0b\'``` prefix to represent a binary number, we subtract that from the length of the binary string for 5, which Python presents as ```\'0b101\'```.*\n\n## Faster Complement with Bitshift\nWe can calculate 2^N much faster by bitshifting a 1. Since 2^N in binary is just 1 followed by N zeroes (same as in decimal, where 10^N is just 1 followed by N zeroes), we can replace 2^N with 1<<. So now we have:\n```\n(1<<(len(bin(num))-2)) - 1 - num\n```\nAnd finally, as noted before, ```~num = -(num+1)```, so we can replace this term in our code for elegance.\n```\n(1<<(len(bin(num))-2)) + ~num\n```\n\n# Time Comparison\nI used Python\'s ```timeit``` module to compare the various methods. For this test, I set it up with 500 random integers sampled from [0,100000000] and ran it 5000 times, repeating each test 5 times. Results:\n* Brute Force: **33.0518s**\n* 2^N Complement: **5.8786s**\n* Bitshift Complement: **3.7803s**\n\n*I also compared using ```~num``` vs ```-num-1```, but the results were roughly equal.*\n\n\n
6
1
['Bit Manipulation', 'Python', 'Python3']
0
number-complement
Java | 100% Faster | With Comments
java-100-faster-with-comments-by-onefine-4pkw
```\nclass Solution {\n public int findComplement(int num) {\n int result = 0;\n //use set to set the value of result in each bit\n int
onefineday01
NORMAL
2020-05-04T07:40:10.633903+00:00
2020-05-04T07:40:25.379383+00:00
1,335
false
```\nclass Solution {\n public int findComplement(int num) {\n int result = 0;\n //use set to set the value of result in each bit\n int set = 1;\n while(num != 0) {\n //if last bit is 0 , set corresponding position of result to 1\n if((num&1)== 0) {\n result |= set;\n }\n //if last bit of num is 1, then do not need to set result\n set <<= 1; // left shift 1 bit\n num >>= 1;//right shift num, move right 1 bit\n }\n return result;\n }\n}
6
0
['Java']
0
number-complement
One-line JavaScript solution
one-line-javascript-solution-by-john015-naam
javascript\n// One-line solution\nvar findComplement = function(num) {\n return num ^ parseInt(\'1\'.repeat(num.toString(2).length), 2)\n};\n\n// Two-line so
john015
NORMAL
2019-08-15T12:35:30.357388+00:00
2019-08-15T12:37:17.809868+00:00
309
false
```javascript\n// One-line solution\nvar findComplement = function(num) {\n return num ^ parseInt(\'1\'.repeat(num.toString(2).length), 2)\n};\n\n// Two-line solution\nvar findComplement = function(num) {\n\tconst mask = \'1\'.repeat(num.toString(2).length)\n return num ^ parseInt(mask, 2)\n};\n```\n\n
6
0
['JavaScript']
0
number-complement
Layman's conversion method: Decimal to binary, complement and back to Decimal
laymans-conversion-method-decimal-to-bin-eqxh
Long approach.\nNot used any Math.func , XOR, Bit manipulation.\n1.Convert Decimal to binary.\n2.Take its compliment\n3.Convert back to equivalent Decimal.\n\n\
idkwho
NORMAL
2019-02-20T11:28:03.022182+00:00
2019-02-20T11:28:03.022225+00:00
5,374
false
Long approach.\nNot used any Math.func , XOR, Bit manipulation.\n1.Convert Decimal to binary.\n2.Take its compliment\n3.Convert back to equivalent Decimal.\n\n```\nclass Solution {\n public int findComplement(int num) {\n int sum=0;\n List<Integer> n = new ArrayList<Integer>();\n //Convert Decimal to Binary\n while(num!=0)\n {\n n.add(num%2);\n num = num/2;\n if(num==1)\n {\n n.add(num);\n num=0;\n } \n }\n //Complement it\n for(int i=0;i<n.size();i++)\n {\n if(n.get(i)==1)\n {\n n.set(i,0);\n }else\n {\n n.set(i,1);\n }\n }\n //Convert back to decimal\n int count=1;\n for(int i=0;i<n.size();i++)\n {\n sum += n.get(i)*count;\n count *= 2;\n }\n return sum;\n }\n}\n```
6
0
[]
0
number-complement
Share my Java solution with explanation
share-my-java-solution-with-explanation-t8pji
\npublic int findComplement(int num) {\n // find highest one bit\n\tint id = 31, mask = 1<<id;\n\twhile ((num & mask)==0) mask = 1<<--id;\n\t\t\n\t// mak
shawnloatrchen
NORMAL
2017-01-10T16:16:08.071000+00:00
2017-01-10T16:16:08.071000+00:00
2,113
false
```\npublic int findComplement(int num) {\n // find highest one bit\n\tint id = 31, mask = 1<<id;\n\twhile ((num & mask)==0) mask = 1<<--id;\n\t\t\n\t// make mask\n\tmask = (mask<<1) - 1;\n\t\t\n\treturn (~num) & mask;\n}\n```
6
0
[]
0
number-complement
❤️‍🔥 Python3 💯 JavaScript 🔥 C++ Solution
python3-javascript-c-solution-by-zane361-g72c
Intuition\n Describe your first thoughts on how to solve this problem. \nFirstly, we need to convert decimal number to binary number. \nSecondly, we will change
shomalikdavlatov
NORMAL
2024-08-22T10:18:04.619684+00:00
2024-08-22T10:18:04.619712+00:00
317
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirstly, we need to convert decimal number to binary number. \nSecondly, we will change `0` to `1` and `1` to `0`.\nLastly, we will convert this number to decimal number and return it.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, I thought about it and realized that I have to write code to convert decimal to binary and vice versa.\n\nThen, I thought about built-in functions and there were!\n\nThe `bin(int)` function takes decimal number and returns binary version of it starting with `0b`\nThe `int(bin, 2)` function takes binary string from `bin()` function and converts it to decimal\n\n# Complexity\n- Time complexity: `O(log n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this solution is O(log n) where n is the input number. This is because we are converting the input number to its binary representation, which requires log n operations. Additionally, we are performing string manipulation operations on the binary representation, which also take O(log n) time.\n\n- Space complexity: `O(log n)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity of this solution is O(log n) as well. This is because we are storing the binary representation of the input number as a string, which requires O(log n) space. Additionally, we are creating a new string to store the complement of the binary representation, which also takes O(log n) space.\n\n# Code\n```python3 []\nclass Solution:\n def findComplement(self, num: int) -> int:\n num = bin(num)\n num = num[2:]\n num = num.replace(\'1\', \' \')\n num = num.replace(\'0\', \'1\')\n num = num.replace(\' \', \'0\')\n num = \'0b\' + num\n return int(num, 2)\n\n```\n```JavaScript []\n/**\n * @param {number} num\n * @return {number}\n */\nvar findComplement = function(num) {\n // Convert the number to a binary string\n let binaryStr = num.toString(2);\n let complementStr = \'\';\n\n // Flip the bits: \'1\' to \'0\' and \'0\' to \'1\'\n for (let char of binaryStr) {\n complementStr += (char === \'1\') ? \'0\' : \'1\';\n }\n\n // Convert the complemented binary string back to a decimal integer\n return parseInt(complementStr, 2);\n};\n```\n```C++ []\nclass Solution {\npublic:\n int findComplement(int num) {\n // Create a mask with all bits set to 1 where the original number has bits\n int mask = 0;\n int temp = num;\n\n // Create the mask by shifting 1 left and ORing with mask until temp is 0\n while (temp > 0) {\n mask = (mask << 1) | 1;\n temp >>= 1;\n }\n\n // XOR the number with the mask to get the complement\n return num ^ mask;\n }\n};\n```\n\n
5
0
['C++', 'Python3', 'JavaScript']
1
number-complement
Easy C solution with explanation beats 100% user in speed||Number Complement
easy-c-solution-with-explanation-beats-1-f2c8
Intuition\n Describe your first thoughts on how to solve this problem. \nAs usual here\'s the proof of the speed: \n\nThe idea is to create a bit mask made of 1
Skollwarynz
NORMAL
2024-08-22T08:24:13.116868+00:00
2024-08-22T08:24:13.116909+00:00
169
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs usual here\'s the proof of the speed: \n![image.png](https://assets.leetcode.com/users/images/77f3c969-f0ff-4bec-88c5-76a98ca5e2f4_1724313803.656143.png)\nThe idea is to create a bit mask made of 1 long as the bit representation of num then use the XOR operation and invert the bit. \n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo do what we tought we have to create a mask:\n```\n int mask=0;\n```\nThen create a cycle that check when the number of bit in "num" is finished:\n```\n while((num & ~mask) != 0){\n mask = (mask << 1) | 1;\n }\n```\nActually I tried to create the right condiction of this cycle but I fixed my errors using Chatgpt but here\'s my explanation: the idea is simple until the logic operation "&" continues to give result 1 it means that the bit is not yet finished, because the operation "&" is the operation bit per bit so: \n```\nnum=5 -----> 00000101\nmask=0 ----> 00000000\n 1) first cycle:\n 00000101 & !(00000000) = 00000101 & 11111111 --> 5!=0 \n num=5 ------> 00000101\n mask=0 -----> 00000001\n 2) second cycle:\n 00000101 & !(00000001) = 00000101 & 11111110 --> 4!=0 \n num=5 ------> 00000101\n mask=0 -----> 00000011 \n 3) third cycle:\n 00000101 & !(00000011) = 00000101 & 11111100 --> 4!=0 \n num=5 ------> 00000101\n mask=0 -----> 00000111 \n 4) fourth cycle: \n 00000101 & !(00000011) = 00000101 & 11111000 --> 0==0\nThe cycle is done!\n```\nAfter this simulation handmade I hope the functioning of the cycle is clear. The last step is to use the XOR operation to return the value researched and why the XOR? Beacause his table of truth is the only one that return 1 when 2 bit are opposite and 0 when they\'re equal:\n```\nTable of truth:\n | XOR | A | B |\n | 0 | 0 | 0 |\n | 1 | 1 | 0 |\n | 1 | 0 | 1 |\n | 0 | 1 | 1 |\n```\nSo we return: \n```\n return num ^ mask;\n```\nAnd we\'re done, please upvote tu support me :)\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 []\nint findComplement(int num) {\n int mask=0;\n while((num & ~mask) != 0){\n mask = (mask << 1) | 1;\n }\n return num ^ mask;\n}\n```
5
0
['Bit Manipulation', 'C']
0
number-complement
Simple and Easy C++ Code 💯☠️
simple-and-easy-c-code-by-shodhan_ak-25dj
\n\n# Code\ncpp []\nclass Solution {\npublic:\n int findComplement(int num) {\n bitset<32> binary(num);\n string ans = binary.to_string();\n
Shodhan_ak
NORMAL
2024-08-22T05:30:07.702346+00:00
2024-08-22T05:30:07.702376+00:00
642
false
\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int findComplement(int num) {\n bitset<32> binary(num);\n string ans = binary.to_string();\n string res = "";\n bool f1 = false;\n for (int i = 0; i < ans.size(); ++i) {\n if (ans[i] == \'1\') {\n f1 = true;\n }\n if (f1) {\n if (ans[i] == \'0\') {\n res += \'1\';\n } else {\n res += \'0\';\n }\n }\n }\n return stoi(res, NULL, 2);\n }\n};\n```\n# Problem Understanding\nThe goal is to find the bitwise complement of a given integer num. The bitwise complement flips all the bits of the binary representation of num. For example:\n\nFor num = 5, which in binary is 00000000000000000000000000000101, the bitwise complement is 11111111111111111111111111111010, which in decimal is 2.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**Binary Representation:**\n\nFirst, convert the given integer num to its binary representation. This can be efficiently done using bitset<32>, which represents the number as a 32-bit binary string.\n\n**String Manipulation:**\n\nConvert this binary representation to a string using binary.to_string(). This string will be 32 characters long, with leading zeros.\n\n**Finding the Leading Bit:**\n\nIterate through the string to find the first occurrence of 1 (f1 flag is used to indicate this). All the leading zeros before the first 1 are irrelevant for the complement calculation.\n\n**Flipping the Bits:**\n\nStart from the first 1 found and flip the bits: convert 0 to 1 and 1 to 0.\n\n**Forming the Result:**\n\nConstruct the resulting string after flipping the relevant bits.\n\n**Convert Back to Integer:**\n\nConvert the resulting binary string back to an integer using stoi(res, NULL, 2) where res is the string of flipped bits.\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)$$ -->
5
0
['C++']
0
number-complement
✅Easy C++ Solution with Video Explanation✅
easy-c-solution-with-video-explanation-b-q3d5
Video Explanation\nhttps://youtu.be/1X7p3EDVrks?si=X1WTUiktBZ3sARbO\n# Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requ
prajaktakap00r
NORMAL
2024-08-22T01:22:05.406401+00:00
2024-08-22T01:22:05.406450+00:00
2,793
false
# Video Explanation\nhttps://youtu.be/1X7p3EDVrks?si=X1WTUiktBZ3sARbO\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires finding the complement of a number in its binary form, which involves flipping all the bits (i.e., turning 0s into 1s and 1s into 0s). To achieve this, we need to isolate the bits of the number that are relevant (i.e., the bits that represent the number) and flip only those.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Edge Case Handling:** If num is 0, its complement is 1 because flipping no bits (since there are no 1s) effectively gives us 1. This is handled with a simple conditional check at the start.\n2. **Bitmask Initialization:** We start with a bitmask that has all bits set to 1. The bitmask is created using ~0, which results in a value where all bits are 1 in binary.\n3. **Shifting the Bitmask:** The goal is to shift the bitmask left until it aligns with the number of bits used by num. We repeatedly shift the bitmask left until num & bitmask results in 0. This ensures that the bitmask has zeroes in the positions corresponding to the significant bits of num.\n4.** Flipping Bits:** Once the bitmask is correctly aligned, we flip the bits of num using the XOR operation with ~bitmask. The ~bitmask has 1s only in positions where num has significant bits, so the XOR operation flips only these bits, leaving the rest unchanged.\n5. **Return the Result:** The XOR result is the complement of num, which is returned as the final answer.\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```cpp []\nclass Solution {\npublic:\n int findComplement(int num) {\n if (num == 0) return 1; \n\n unsigned int bitmask = ~0; \n \n \n while (num & bitmask) {\n bitmask <<= 1;\n }\n\n \n return num ^ ~bitmask;\n }\n};\n\n```
5
1
['C++']
1
number-complement
100 % Faster Solution
100-faster-solution-by-2005115-0ygf
PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT\n# CONNECT WITH ME\n### https://www.linkedin.com/in/pratay-nandy-9ba57b229/\n#### https://www.instagram.com/pratay_nand
2005115
NORMAL
2023-10-13T05:43:43.779071+00:00
2023-10-13T05:43:43.779089+00:00
613
false
# **PLEASE UPVOTE MY SOLUTION IF YOU LIKE IT**\n# **CONNECT WITH ME**\n### **[https://www.linkedin.com/in/pratay-nandy-9ba57b229/]()**\n#### **[https://www.instagram.com/pratay_nandy/]()**\n\n# Approach\nHere\'s a step-by-step explanation of the approach used in this code:\n\n1. Initialize `m` to the value of `n`. `m` will be used to calculate the length of the binary representation of `n`.\n\n2. Check if `m` is equal to 0. If `n` is 0, its bitwise complement is 1. In this case, the function directly returns 1.\n\n3. Initialize a variable `mask` to 0. The `mask` variable is used to create a bit mask of 1s with the same length as the binary representation of `n`.\n\n4. Use a `while` loop to calculate the `mask`:\n - In each iteration, `mask` is left-shifted by 1 bit and then bitwise ORed with 1. This effectively adds a \'1\' to the `mask`.\n - The loop continues until `m` becomes 0. This loop calculates a bit mask with all 1s, and the length of the mask is equal to the number of bits required to represent `n`.\n\n5. Calculate the bitwise complement of `n`:\n - `(~n)` computes the bitwise negation of `n`, changing all 0s to 1s and all 1s to 0s.\n - `& mask` performs a bitwise AND operation between the negated value and the mask. This operation sets all bits in `n` to 0 except for the least significant bits that are part of the binary representation of `n`.\n\n6. Return the result, which is the bitwise complement of the input integer `n`.\n\nThis code successfully calculates the bitwise complement of an integer `n` by creating a mask with the same length as the binary representation of `n` and then applying the negation and bitwise AND operations.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:**0(N)**\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**0(1)**\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int findComplement(int n) {\n int m = n;\n if(m==0)return 1;\n int mask = 0 ;\n while(m!=0)\n {\n mask = (mask << 1) | 1;\n m = m >> 1;\n }\n int ans = (~n) & mask; \n return ans;\n }\n};\n```\n![upvote.png](https://assets.leetcode.com/users/images/110e7ddb-8c49-4d9d-a981-30402851fd45_1697175766.2120907.png)\n
5
0
['Bit Manipulation', 'C', 'C++']
0
number-complement
JAVA - 2 line with Explanation - Bit Manipulation - 0ms
java-2-line-with-explanation-bit-manipul-u0fx
Num + Complement = All 1\'s\nSo, Complement = All 1\'s - Num\n\nExample :\nnum = 5 = 101\ncomplement = 2 = 010\n\n101 + 010 = 111\n101 + complement = 111\nSo, c
Its_Smriti
NORMAL
2022-12-10T17:07:12.723889+00:00
2022-12-10T17:07:12.723924+00:00
1,137
false
Num + Complement = All 1\'s\nSo, Complement = All 1\'s - Num\n\n**Example :**\nnum = 5 = 101\ncomplement = 2 = 010\n\n101 + 010 = 111\n**101 + complement = 111\nSo, complement = 111 - 101\n = 010**\n\n# Code\n```\nclass Solution {\n public int findComplement(int num) {\n int n = 0;\n while (n < num) {\n n = (n << 1) | 1;\n }\n return n - num;\n }\n}\n```
5
0
['Bit Manipulation', 'Java']
1
number-complement
Python Simple Solution Faster Than 97.39%
python-simple-solution-faster-than-9739-kc0ny
\nclass Solution:\n def findComplement(self, num: int) -> int:\n s=bin(num).replace(\'0b\',\'\')\n t=\'\'\n for i in s:\n if
pulkit_uppal
NORMAL
2022-10-26T00:09:58.976542+00:00
2022-10-26T00:09:58.976576+00:00
633
false
```\nclass Solution:\n def findComplement(self, num: int) -> int:\n s=bin(num).replace(\'0b\',\'\')\n t=\'\'\n for i in s:\n if i==\'0\':\n t+=\'1\'\n else:\n t+=\'0\'\n return int(t,2)\n```
5
0
['Python']
0
number-complement
C++ XOR solution with detail explain
c-xor-solution-with-detail-explain-by-zh-obpx
Consider the 32-bit int number representing as follow:\n 0000 0000 0000 0000 0000 0000 0000 0101 ----> num\n 0111 1111 1111 1111 1111 1111 1111 1111 ----> mas
zhxilin
NORMAL
2021-03-28T08:24:32.475900+00:00
2021-03-28T08:24:54.472405+00:00
570
false
Consider the 32-bit int number representing as follow:\n* 0000 0000 0000 0000 0000 0000 0000 0101 **---->** **num**\n* 0111 1111 1111 1111 1111 1111 1111 1111 **---->** **mask** **---->** *key problem to calculate the mask*\n* 0111 1111 1111 1111 1111 1111 1111 1010 **---->** **complement = num XOR mask**\n\t\n```\n int findComplement(int num) {\n\t //First calculate the bit counts of num using log2()\n unsigned int bits = floor(log2(num)) + 1;\n\t\t//Create a mask of pow(2, bits) - 1.\n\t\t//XOR the mask and the original num will get the complement number.\n return ((unsigned int)(1 << bits) - 1) ^ num;\n }\n```\n\nIf you like it, please upvote.
5
1
['Bit Manipulation', 'C', 'C++']
3
number-complement
JavaScript solution beats 100% using string
javascript-solution-beats-100-using-stri-pnux
\nvar findComplement = function(num) {\n var str = num.toString(2);\n var result = \'\';\n for (var i of str) {\n result += i === \'1\'? \'0\': \
ys2843
NORMAL
2018-06-04T17:38:43.647975+00:00
2018-06-04T17:38:43.647975+00:00
338
false
```\nvar findComplement = function(num) {\n var str = num.toString(2);\n var result = \'\';\n for (var i of str) {\n result += i === \'1\'? \'0\': \'1\';\n }\n return parseInt(result, 2);\n};\n```
5
0
[]
0
number-complement
C# - 3 lines - O(highest set bit)
c-3-lines-ohighest-set-bit-by-jdrogin-ul0d
\nthe complexity will be the number of digits up to the highest set bit.\n\n\n public int FindComplement(int num) \n {\n int mask = 1;\n whi
jdrogin
NORMAL
2017-01-12T21:01:29.762000+00:00
2017-01-12T21:01:29.762000+00:00
861
false
\nthe complexity will be the number of digits up to the highest set bit.\n\n```\n public int FindComplement(int num) \n {\n int mask = 1;\n while (mask < num) mask = (mask << 1) | 1;\n return ~num & mask;\n }\n```
5
0
[]
0
number-complement
Java, O(N) solution, easy to understand with detailed explanation and comments
java-on-solution-easy-to-understand-with-s1a8
idea is simple, check each bit from right to leftmost bit 1, if bit is 1, continue, if bit is 0, set result's corresponding bit to 1\n```\npublic class Solution
jim39
NORMAL
2017-01-18T20:28:48.469000+00:00
2017-01-18T20:28:48.469000+00:00
801
false
idea is simple, check each bit from right to leftmost bit 1, if bit is 1, continue, if bit is 0, set result's corresponding bit to 1\n```\npublic class Solution {\n public int findComplement(int num) {\n int result = 0;\n //use set to set the value of result in each bit\n int set = 1;\n while(num != 0) {\n //if last bit is 0 , set corresponding position of result to 1\n if((num&1)== 0) {\n result |= set;\n }\n //if last bit of num is 1, then do not need to set result\n set <<= 1; // left shift 1 bit\n num >>= 1;//right shift num, move right 1 bit\n }\n return result;\n }\n}
5
0
['Bit Manipulation', 'Java']
1
number-complement
easy to understand bitwise approach with explanation || c++ || JS || python || python3
easy-to-understand-bitwise-approach-with-qo0r
Intuition\nThe complement of a number in binary is obtained by flipping all bits (i.e., converting 0s to 1s and 1s to 0s). To efficiently compute the complement
aramvardanyan13
NORMAL
2024-08-22T10:36:43.083327+00:00
2024-09-03T14:49:58.082008+00:00
245
false
# Intuition\nThe complement of a number in binary is obtained by flipping all bits (i.e., converting `0`s to `1`s and `1`s to `0`s). To efficiently compute the complement of a number, we need to focus only on the bits that matter\u2014those that correspond to the binary representation of the number.\n\n# Approach\n1. **Identify the Most Significant Bit (MSB):**\n - First, identify the position of the `most significant bit (MSB)` that is set to `1` in the given number. This is the highest bit position where `1` appears in the binary representation.\n2. **Flip the Bits:**\n - To get the complement, we need to flip all the bits from the `least significant bit (LSB)` up to the `MSB`. We can achieve this by using `XOR (^)` operation with a number that has all bits set to `1` up to the position of the `MSB`.\n3. Return the Result:\n - The result after flipping the relevant bits will be the complement of the original number.\n\n\n\n\n# Complexity\n- Time complexity: $$O(1)$$ since the algorithm only involves a few bitwise operations that run in constant time.\n\n- Space complexity: $$O(1)$$ because no extra space proportional to the input size is required.\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int findComplement(int num) \n {\n int ind = 0; // Variable to store the position of the most significant bit (MSB)\n\n // Loop to find the MSB where \'1\' is present\n for (int i = 0; i < sizeof(int) * 8; ++i)\n {\n // Check if the bit at position \'i\' is set to 1\n if (num & (1 << i))\n {\n ind = i; // Update \'ind\' to the current position of the set bit\n }\n }\n\n // Loop to flip all bits from the least significant bit (LSB) up to the MSB\n for (int i = 0; i <= ind; ++i)\n {\n // Flip the bit at position \'i\' using XOR\n num = num ^ (1 << i);\n }\n\n return num; // Return the complement of the original number\n }\n};\n```\n```javascript []\n/**\n * @param {number} num\n * @return {number}\n */\nvar findComplement = function(num) {\n let ind = 0;\n\n // Find the highest bit that is set\n for (let i = 0; i < 32; i++) {\n if (num & (1 << i)) {\n ind = i;\n }\n }\n\n // Flip all bits up to the highest bit set\n for (let i = 0; i <= ind; i++) {\n num = num ^ (1 << i);\n }\n\n return num;\n};\n```\n```python3 []\nclass Solution:\n def findComplement(self, num: int) -> int:\n ind: int = 0\n\n # Find the highest bit that is set\n for i in range(32):\n if num & (1 << i):\n ind = i\n\n # Flip all bits up to the highest bit set\n for i in range(ind + 1):\n num ^= (1 << i)\n\n return num\n \n```\n\n\n\n\n
4
0
['Python', 'C++', 'Python3', 'JavaScript']
0
number-complement
Java Simple Brute Force Approach
java-simple-brute-force-approach-by-chai-040r
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem asks us to find the complement of a given integer. The complement of a bina
Chaitanya_91
NORMAL
2024-08-22T09:20:18.155380+00:00
2024-08-22T09:20:18.155411+00:00
50
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem asks us to find the complement of a given integer. The complement of a binary number is obtained by flipping all the bits (i.e., converting 0s to 1s and 1s to 0s). The basic idea is to convert the number into its binary form, flip the bits, and then convert it back to a decimal number.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nConvert the given integer num to its binary representation.\nIterate through each bit of the binary number:\nIf the bit is 1, change it to 0.\nIf the bit is 0, change it to 1.\nConvert the modified binary string back to a decimal number, which will be the complement of the original number.\n\n# Complexity\n- Time complexity: O(logn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(logn)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int findComplement(int num) {\n StringBuilder s = new StringBuilder();\n while (num > 0) {\n int t = num % 2;\n s.insert(0, t);\n num /= 2;\n }\n for (int i = 0; i < s.length(); i++) {\n if (s.charAt(i) == \'1\') {\n s.setCharAt(i, \'0\');\n }\n else {\n s.setCharAt(i, \'1\');\n }\n }\n return Integer.parseInt(s.toString(), 2);\n }\n}\n\n```
4
0
['Java']
0
number-complement
Kotlin. Beats 100% (112 ms). Calculate mask then xor.
kotlin-beats-100-112-ms-calculate-mask-t-kjr5
\n\n# Code\nkotlin []\nclass Solution {\n fun findComplement(num: Int): Int {\n var n = num\n var mask = 0\n while (n != 0) {\n
mobdev778
NORMAL
2024-08-22T08:18:04.742568+00:00
2024-08-22T09:10:54.756572+00:00
170
false
![image.png](https://assets.leetcode.com/users/images/88f7af03-8085-48b9-a76d-cace91b46c59_1724314389.2553186.png)\n\n# Code\n```kotlin []\nclass Solution {\n fun findComplement(num: Int): Int {\n var n = num\n var mask = 0\n while (n != 0) {\n n = n shr 1\n mask = mask shl 1 or 1\n }\n return num xor mask\n }\n}\n```\n\n# Approach\n\nThe algorithm is simple - we must first calculate a mask of ones for all the bits that are included in the given number. For example, for the number 5 (101b) this will be a mask of 7 (111b).\n\nThe next step is to XOR the mask and the number so that the result will be bits that are not included in the initial number:\n\n```\n111 x 101 = 010\n```\n\n010b = 2\n\n# Alternative approaches\n\n1. "Integer.takeHighestOneBit".\n\nAlternatively, we can use the "Integer.takeHighestOneBit()" operation with a pre-computed set of masks for all 32 variants, but it is slower, because the "Integer.takeHighestOneBit()" operation does a lot of calculations internally (bitwise shifts).\n\n![image.png](https://assets.leetcode.com/users/images/720f9328-d269-4102-bf92-43a9a56ab379_1724315876.705344.png)\n\n```\nclass Solution {\n fun findComplement(num: Int): Int {\n return num xor (masks[num.takeHighestOneBit()] ?: 0)\n }\n\n companion object {\n val masks = TreeMap<Int, Int>()\n\n init {\n for (i in 0..32) {\n val bit = 1 shl i\n masks.put(bit, (bit shl 1) - 1)\n }\n }\n }\n}\n```\n\n2. Direct xoring \n\n![image.png](https://assets.leetcode.com/users/images/2d8d1fae-8b44-4002-9bb4-dfeae013b2d7_1724316755.4818318.png)\n\n```\nclass Solution {\n fun findComplement(num: Int): Int {\n var n = num\n\n var result = 0\n var offset = 0\n for (i in 0 until 31) {\n if (n == 0) break\n val bit = (n and 1) xor 1\n result = result or (bit shl offset)\n offset++\n n = n shr 1\n }\n\n return result\n }\n}\n```\n\n3. Direct xoring #2\n\n![image.png](https://assets.leetcode.com/users/images/22b0bcb8-52b6-465c-a808-ae1159f40b84_1724316979.7803967.png)\n\n```\nclass Solution {\n fun findComplement(num: Int): Int {\n var n = num\n\n var result = 0\n for (i in 0 until 31) {\n if (n == 0) break\n result = result or ((1 shl i xor num) and (1 shl i))\n n = n shr 1\n }\n\n return result\n }\n}\n```\n\n4. Direct xoring #3\n\nIt is also worth noting that we do not use the 31st bit, since it is the sign bit.\n\n![image.png](https://assets.leetcode.com/users/images/faecf1ca-7fe2-4f79-b066-5a8f42d94365_1724317734.227085.png)\n\n```\nclass Solution {\n fun findComplement(num: Int): Int {\n var result = 0\n for (i in 0 until 31) {\n val bit = 1 shl i\n if (bit > num) break\n result = result or ((num and bit) xor bit)\n }\n return result\n }\n}\n```
4
0
['Kotlin']
1
number-complement
Python | Bit Manipulation
python-bit-manipulation-by-khosiyat-pa4j
see the Successfully Accepted Submission\n\n# Code\npython3 []\nclass Solution(object):\n def findComplement(self, num):\n \n compliment = 1\n
Khosiyat
NORMAL
2024-08-22T07:01:41.681453+00:00
2024-08-22T07:01:41.681487+00:00
733
false
[see the Successfully Accepted Submission](https://leetcode.com/problems/number-complement/submissions/943115373/?envType=daily-question&envId=2024-08-22)\n\n# Code\n```python3 []\nclass Solution(object):\n def findComplement(self, num):\n \n compliment = 1\n while compliment <= num:\n compliment = compliment << 1\n \n leftCompliment=compliment - 1\n compliment=(leftCompliment) ^ num\n \n return compliment\n \n```\n\n# Step-by-Step Breakdown\n\n### Initialization:\n- A variable `compliment` is initialized to `1`. This variable is used to find a mask that can cover all the bits of `num`.\n\n### Calculate the Bit Mask:\n- The `while` loop runs until `compliment` is greater than `num`. In each iteration, `compliment` is left-shifted by 1 position (`compliment = compliment << 1`), effectively doubling its value. This continues until `compliment` exceeds `num`. The purpose of this loop is to determine a mask that has all bits set to `1` up to the leftmost bit of `num`.\n\n### Mask Calculation:\n- After the loop, `compliment` will be a power of 2 that is just greater than `num`. The mask, `leftCompliment`, is then calculated as `compliment - 1`. This mask will have all bits set to `1` up to the same bit length as `num`.\n\n### Compute the Complement:\n- The complement of `num` is calculated by performing a bitwise XOR between `leftCompliment` and `num`. The XOR operation flips the bits of `num` where the mask has bits set to `1`.\n\n### Return the Complement:\n- Finally, the method returns the computed complement.\n\n## Example\n\nLet\u2019s consider an example to illustrate how this works:\n\n- Suppose `num = 5`, which in binary is `101`.\n- The `compliment` variable will progress as follows:\n - Initially: `compliment = 1` (binary `001`)\n - After first shift: `compliment = 2` (binary `010`)\n - After second shift: `compliment = 4` (binary `100`)\n - After third shift: `compliment = 8` (binary `1000`, greater than `101`)\n- The `leftCompliment` mask is `8 - 1 = 7` (binary `111`).\n- The XOR operation: `7 ^ 5 = 2` (binary `010`).\n\nThus, the method returns `2`, which is the bitwise complement of `5`.\n\n## Complexity\n\n- **Time Complexity**: `O(n)`, where `n` is the number of bits in `num`.\n- **Space Complexity**: `O(1)`, as we use a constant amount of space.\n\n\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)
4
1
['Python3']
0
number-complement
🌟 Efficient Solution for "Number Complement" | C++ | 0ms Beats 100.00% | O(log n)
efficient-solution-for-number-complement-pgpu
\n---\n# Intuition\n\nThe problem requires finding the complement of a given integer. The complement is obtained by flipping all bits in the binary representati
user4612MW
NORMAL
2024-08-22T04:08:51.835330+00:00
2024-08-22T04:08:51.835359+00:00
19
false
##\n---\n# Intuition\n\nThe problem requires finding the complement of a given integer. The complement is obtained by flipping all bits in the binary representation of the number.\n\n# **Approach**\n\nTo find the complement of an integer **num**, first determine the number of bits needed to represent **num** in binary. Create a bitmask with all bits set to 1, matching this length. Apply a bitwise NOT operation to **num**, and then use bitwise AND with the bitmask to obtain the complement. This method efficiently computes the result by leveraging bitwise operations.\n\n# Complexity\n- **Time Complexity** $$O(\\log n)$$ The operations are based on the number of bits in the integer.\n- **Space Complexity** $$O(1)$$ Only a few additional variables are used.\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int findComplement(int num) {\n int number = num,bitmask = pow(2, ceil((double)log2(number))) - 1;\n return (~number) & bitmask;\n }\n};\n\n```\n---\n## **If you found this solution helpful, please upvote! \uD83D\uDE0A**\n---\n
4
0
['C++']
0
number-complement
C# Solution for Number Complement Problem
c-solution-for-number-complement-problem-xv39
Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to flip all the bits in the binary representation of an integer, effectivel
Aman_Raj_Sinha
NORMAL
2024-08-22T03:07:21.448878+00:00
2024-08-22T03:07:21.448913+00:00
258
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to flip all the bits in the binary representation of an integer, effectively calculating its complement. The approach involves generating a bitmask that has the same number of bits as the input integer but with all bits set to 1. By XORing this mask with the original number, the bits are flipped to achieve the complement.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.\tMask Construction:\n\t\u2022\tBegin with a mask initialized to 1.\n\t\u2022\tGradually build a mask that has all bits set to 1 for the length of the binary representation of num.\n\t\u2022\tThis is done by repeatedly left-shifting the mask (which effectively multiplies it by 2) and then adding 1 using the OR operation (| 1). This process continues until the mask is greater than or equal to num.\n2.\tXOR Operation:\n\t\u2022\tOnce the mask is constructed, XOR the original num with the mask. The XOR operation will flip each bit in num where the corresponding bit in the mask is 1.\n\t\u2022\tThis results in the complement of num.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\u2022\tO(1):\n\t\u2022\tThe mask construction loop runs at most 31 times, as the maximum number of bits in the integer (within the constraints) is 31. This is considered constant time because the number of iterations is fixed and does not grow with the input size.\n\t\u2022\tThe XOR operation is also O(1).\n\t\u2022\tThus, the overall time complexity is constant, O(1).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\u2022\tO(1):\n\t\u2022\tThe solution uses a constant amount of additional space, only requiring a few integer variables (mask and num).\n\t\u2022\tThere are no extra data structures or dynamically allocated memory, so the space complexity remains constant.\n\n# Code\n```csharp []\npublic class Solution {\n public int FindComplement(int num) {\n // Initialize mask as 1\n int mask = 1;\n\n // Generate a mask with all bits set to 1 that covers the length of num\'s binary representation\n while (mask < num) {\n mask = (mask << 1) | 1;\n }\n\n // XOR num with the mask to get the complement\n return num ^ mask;\n }\n}\n```
4
0
['C#']
0
number-complement
Number Complement - Beats 100% - Unique and Easy solution 🌟🔜
number-complement-beats-100-unique-and-e-k356
Intuition\nIf we find remainder when divided the number by 2,it\'ll give the bit representation in reverse order.With that ,we\'ll calculate the complement of t
RAJESWARI_P
NORMAL
2024-08-22T00:54:40.772844+00:00
2024-08-22T00:54:40.772864+00:00
142
false
# Intuition\nIf we find remainder when divided the number by 2,it\'ll give the bit representation in reverse order.With that ,we\'ll calculate the complement of the number by converting that binary representation to integer by multiplying with powers of 2 if the remainder obtained is 0.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n - The idea is to apply the technique to convert decimal to binary.\n - Initialize newnum to 0 which is the complement of the given number.\n - So find the remainder of the given number when divided by 2.\n - With that remainder,if it is \'0\' ,to find the complement ,actually it must be changed to 1.\n - Add to the newnum,the powers of 2 with initializing base (In our case k to 0),then at iteration multiply k by 2.\n - Then to find next bit of the number from right,divide the number by 2 in each iteration. \n - The iteration is repeated till the number is greater than 0.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:**O(log n)**.\n n ->value of the number num.\n- The iteration repeats till the number of bits of n which is proportional to **log2(n)**.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**O(1)**.\n- No additional datastructure doesn\'t require hence the space required doesn\'t depend on input size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int findComplement(int num) {\n int newnum=0;\n int k=1;\n while(num>0)\n {\n int r=num%2;\n //System.out.println(r);\n if(r==0)\n {\n \n newnum+=k;\n \n }\n k*=2;\n num=num/2;\n }\n \n return newnum;\n\n }\n}\n```
4
0
['Bit Manipulation', 'Java']
0
number-complement
No Loop One Line Solution in C++ with 100% m/s
no-loop-one-line-solution-in-c-with-100-v31sb
Intuition\n Describe your first thoughts on how to solve this problem. \n No loop one line solution in c++ just bit manipulation.\n\n# Approach\n Describe yo
shanmukhtharun
NORMAL
2024-08-22T00:42:08.649245+00:00
2024-08-22T00:42:08.649296+00:00
24
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n No loop one line solution in c++ just bit manipulation.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\njust Using the basic bitwise operations to solve the question.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nSolution with O(1).\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nsolution with O(1) Space ,No extra Space.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int findComplement(int n) {\n return n^(2*((1<<int(log2(n)))-1)|1);\n }\n};\n```
4
0
['C++']
0
number-complement
One line solutions
one-line-solutions-by-xxxxkav-7qsd
\nclass Solution:\n def findComplement(self, num: int) -> int:\n return num ^ ((1 << num.bit_length()) - 1)\n\n\nclass Solution:\n def findCompleme
xxxxkav
NORMAL
2024-08-22T00:11:07.228206+00:00
2024-08-22T16:37:13.565785+00:00
1,521
false
```\nclass Solution:\n def findComplement(self, num: int) -> int:\n return num ^ ((1 << num.bit_length()) - 1)\n```\n```\nclass Solution:\n def findComplement(self, num: int) -> int:\n return num ^ (2 ** num.bit_length() - 1)\n```\n```\nclass Solution:\n def findComplement(self, num: int) -> int:\n return num ^ reduce(lambda n, i: n | n >> i, (1, 2, 4, 8, 16), num)\n```\n\n```\nclass Solution:\n def findComplement(self, num: int) -> int: \n return num ^ next(m-1 for m in accumulate(repeat(1), lshift, initial=1) if num < m)\n```\n```\nclass Solution:\n def findComplement(self, num: int) -> int:\n return num ^ 2 ** int(log2(num)) - 1\n```\n```\nclass Solution:\n def findComplement(self, num: int) -> int:\n return ~num + (1 << num.bit_length())\n```\n```\nclass Solution:\n def findComplement(self, num: int) -> int:\n return next(n[0] for n in accumulate(count(0), lambda n,_:(n[0]^n[1], n[1]<<1), initial=(num, 1)) if n[0]<n[1])\n```\n```\nclass Solution:\n def findComplement(self, num: int) -> int:\n return int(\'\'.join(str(1^int(n)) for n in f\'{num:b}\'), 2)\n```
4
1
['Bit Manipulation', 'Bitmask', 'Python3']
2
number-complement
Easy Solution || C++
easy-solution-c-by-japneet001-s1lg
Intuition\nThe code aims to find the complement of a given integer num. The complement is obtained by flipping each bit of the binary representation of the numb
Japneet001
NORMAL
2024-01-31T15:12:16.849898+00:00
2024-01-31T15:12:16.849934+00:00
769
false
# Intuition\nThe code aims to find the complement of a given integer `num`. The complement is obtained by flipping each bit of the binary representation of the number.\n\n# Approach\nThe code iterates through the binary representation of the input `num` one bit at a time. For each bit, it calculates the complement by performing XOR with 1. The complement is then added to the result after being multiplied by the appropriate power of 2. The loop continues until `num` becomes 0.\n\n# Complexity\n- Time complexity: $$O(log(n))$$, where n is the value of the input `num`. The loop runs for each bit in the binary representation of `num`.\n- Space complexity: $$O(1)$$, as only a constant amount of space is used for variables regardless of the input size.\n\n# Code\n```cpp\nclass Solution {\npublic:\n int findComplement(int num) {\n int bit;\n int comp;\n int dec_ans = 0;\n int i = 0;\n while(num != 0){\n bit = num & 1;\n comp = bit ^ 1;\n dec_ans = comp * pow(2, i) + dec_ans;\n num = num >> 1;\n i++;\n }\n\n return dec_ans;\n }\n};\n```
4
0
['Bit Manipulation', 'C++']
0
number-complement
Easy JAVA solution || 3-Line Code || T.C. : O(1) || S.C. : O(1)
easy-java-solution-3-line-code-tc-o1-sc-mw8gl
Intuition\n We are tasked with finding the complement of the given integer \'num\' in binary representation.*\n# Approach\n 1. Convert the given integer \'num\'
Ankita_Chaturvedi
NORMAL
2023-08-12T16:16:45.869535+00:00
2023-08-12T16:17:07.900458+00:00
219
false
# Intuition\n We are tasked with finding the complement of the given integer \'num\' in binary representation.*\n# Approach\n 1. Convert the given integer \'num\' to its binary representation using Integer.toBinaryString(num).\n 2. Calculate the number of bits required to represent \'num\' using the length of its binary representation \'n\'.\n 3. Create a bitmask \'h\' by using the left shift (<<) operator to set all \'n\' bits to 1.\n 4. Calculate the complement by applying the bitwise XOR (^) operation between \'h\' and \'num\'.\n 5. Return the computed complement as the result.\n\n# Complexity\n- Time complexity:\n O(1) because it has a constant number of operations that do not depend on the input size. \n\n- Space complexity: \n The space used for variables and computations is constant, so the space complexity is O(1).\n\n# Code\n```\nclass Solution {\n public int findComplement(int num) {\n int n=Integer.toBinaryString(num).length();\n int h= (1 << n) - 1;\n return h ^ num;\n }\n}\n\n\n```
4
0
['Java']
1
number-complement
Java | Fastest and easiest ever | Linear T & S | Beats 100%
java-fastest-and-easiest-ever-linear-t-s-sir1
Intuition\n Describe your first thoughts on how to solve this problem. \nWe have to flip the bits, i.e. we have to find compliment, thus I think ~n is a really
suryanshhh28
NORMAL
2023-08-05T13:49:20.096881+00:00
2023-08-05T13:49:20.096899+00:00
515
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have to flip the bits, i.e. we have to find compliment, thus I think ~n is a really good option, but we have a problem over here, it flips all the bits that is if an integer only takes 7 bits and rest in front are zeros, it will flip them too which is not required! Thus let\'s find the number of bits in which a number can fit in, suppose we have 20 only, it\'s binary representation is 10100 and by this formula: \n\n##### nBits = (Math.log(num) / Math.log(2)) + 1\n\nWe can get the number of bits in which our number will definitely fit in, thus now let\'s prevent our prefix zeros to flip, thus create a mask \n\n##### mask = (1 << nBits) - 1;\n\nThis will make sure all prefix zeros are preserved, thus let\'s save our zeros now! I hope & will work as it will make 1-0 = 0 and 1-1 = 0, thus & our ~num with our mask\n\n##### ans = ~num & mask\n\nHERE WE GO! LINEAR TIME AND SPACE!\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 {\n public int findComplement(int num) {\n int nBits = (int)Math.floor((Math.log(num) / Math.log(2)) + 1);\n int mask = (1 << nBits) - 1;\n return ~num & mask;\n }\n}\n```
4
0
['Math', 'Bit Manipulation', 'Java']
2
number-complement
Easy Solution using Bitwise Operators
easy-solution-using-bitwise-operators-by-7lwh
```\nclass Solution {\n public static int findComplement(int num) {\n //Q476\n //Ex for 5\n //Using XOR operator - 0-->1 and 1-->0 that
Abhinav_0561
NORMAL
2022-06-07T05:00:20.097376+00:00
2022-06-07T05:00:20.097420+00:00
641
false
```\nclass Solution {\n public static int findComplement(int num) {\n //Q476\n //Ex for 5\n //Using XOR operator - 0-->1 and 1-->0 that is what we need(Complement)\n //101 ^ 111 = 010 i.e., the ans. \n // 111 is the required mask in this case\n //For calculating mask, we take the value of highest one bit\n //5 = 101 in binary. Highest one bit = 100\n //If we left-shift this it will become 1000\n //1000 - 1 = 111 in binary that is the required mask\n int mask = (Integer.highestOneBit(num)<<1) - 1;\n return num ^ mask;\n }\n}
4
0
['Java']
0
number-complement
Number Complement | 100% | Bit Manipulation Approach | Java
number-complement-100-bit-manipulation-a-8t0g
class Solution {\n\n public int findComplement(int n) {\n int number_of_bits = (int) (Math.floor(Math.log(n) / Math.log(2))) + 1;\n return ((1
abhishekjha786
NORMAL
2021-12-27T06:35:03.158502+00:00
2021-12-27T08:37:18.726343+00:00
87
false
class Solution {\n\n public int findComplement(int n) {\n int number_of_bits = (int) (Math.floor(Math.log(n) / Math.log(2))) + 1;\n return ((1 << number_of_bits) - 1) ^ n;\n }\n}\n\n**Please help to UPVOTE if this post is useful for you.\nIf you have any questions, feel free to comment below.\nHAPPY CODING :)\nLOVE CODING :)**
4
1
['Bit Manipulation']
1
number-complement
1-line Go Solution
1-line-go-solution-by-evleria-3ce9
\nfunc findComplement(num int) int {\n\treturn (1<<(bits.Len(uint(num))) - 1) ^ num\n}\n
evleria
NORMAL
2021-11-03T18:47:28.458504+00:00
2021-11-03T18:47:28.458541+00:00
323
false
```\nfunc findComplement(num int) int {\n\treturn (1<<(bits.Len(uint(num))) - 1) ^ num\n}\n```
4
0
['Go']
0
number-complement
simple C 100%
simple-c-100-by-linhbk93-y05t
\nint findComplement(int num){\n int temp = num, c = 0;\n while(temp>0)\n {\n c = (c<<1)|1;\n temp >>= 1;\n } \n return num ^ c;\n
linhbk93
NORMAL
2021-08-25T09:27:03.823737+00:00
2021-08-25T09:27:32.533505+00:00
410
false
```\nint findComplement(int num){\n int temp = num, c = 0;\n while(temp>0)\n {\n c = (c<<1)|1;\n temp >>= 1;\n } \n return num ^ c;\n}\n```
4
0
['C']
0
number-complement
Java Simple Solution 100%
java-simple-solution-100-by-kenzhekozy-6gh7
\nclass Solution {\n public int findComplement(int num) {\n int ans = 0;\n int p = 0;\n while(num!=0){\n if(num%2==0) ans +=
kenzhekozy
NORMAL
2021-03-12T15:31:10.688256+00:00
2021-03-26T10:07:52.953142+00:00
285
false
```\nclass Solution {\n public int findComplement(int num) {\n int ans = 0;\n int p = 0;\n while(num!=0){\n if(num%2==0) ans += Math.pow(2, p);\n p++;\n num /= 2;\n }\n \n return ans;\n }\n}\n\n```
4
0
['Java']
1
number-complement
C++ 100% bitset
c-100-bitset-by-eridanoy-ml5a
\nclass Solution {\npublic:\n int findComplement(int num) {\n bitset<32> b(num);\n int pos=32;\n while(!b[--pos]);\n while(pos>-1
eridanoy
NORMAL
2020-11-17T16:53:30.639945+00:00
2020-11-17T16:53:30.639991+00:00
386
false
```\nclass Solution {\npublic:\n int findComplement(int num) {\n bitset<32> b(num);\n int pos=32;\n while(!b[--pos]);\n while(pos>-1) b.flip(pos--);\n return b.to_ulong();\n }\n};\n```
4
0
['C']
1
number-complement
Easy Java StringBuilder Solution
easy-java-stringbuilder-solution-by-poor-eegk
class Solution {\n public int findComplement(int num) {\n String s=Integer.toBinaryString(num);\n StringBuilder sb=new StringBuilder();\n
poornimadave27
NORMAL
2020-09-18T11:13:45.111281+00:00
2020-09-18T11:13:45.111317+00:00
91
false
class Solution {\n public int findComplement(int num) {\n String s=Integer.toBinaryString(num);\n StringBuilder sb=new StringBuilder();\n for(int i=0;i<s.length();i++){\n if(s.charAt(i)==\'1\'){\n sb.append(\'0\');\n }\n else{\n sb.append(\'1\');\n }\n }\n return (Integer.parseInt(sb.toString(),2));\n }\n}
4
0
[]
0
number-complement
C# simple solution without using Math functions
c-simple-solution-without-using-math-fun-i2pj
\npublic int FindComplement(int num) {\n int k = 1;\n for (int i = num; i > 0; i >>= 1)\n k <<= 1;\n return k - num - 1;\n}\n\n\nif num = 101\nk
alexidealex
NORMAL
2020-05-04T22:48:43.532595+00:00
2020-05-04T22:48:43.532648+00:00
109
false
```\npublic int FindComplement(int num) {\n int k = 1;\n for (int i = num; i > 0; i >>= 1)\n k <<= 1;\n return k - num - 1;\n}\n```\n\nif num = 101\nk will be 1000\nk - 1 = 111\nk - num - 1 = 010\n
4
0
[]
0
number-complement
[Python] Short Bit Solution - Clean & Concise
python-short-bit-solution-clean-concise-obqzk
python\nclass Solution:\n def findComplement(self, num: int) -> int:\n i = 0\n ans = 0\n while num > 0:\n if (num & 1) == 0:\
hiepit
NORMAL
2020-05-04T18:17:03.474147+00:00
2022-04-04T23:46:21.872365+00:00
500
false
```python\nclass Solution:\n def findComplement(self, num: int) -> int:\n i = 0\n ans = 0\n while num > 0:\n if (num & 1) == 0:\n ans |= 1 << i\n i += 1\n num >>= 1\n \n return ans\n```\n**Complexity**\n- Time: `O(logNum)`\n- Space: `O(1)`
4
1
[]
0
number-complement
2 java simple solutions with comments | 100% runtime
2-java-simple-solutions-with-comments-10-nowh
\n1st solution:-\n\nclass Solution {\n public int findComplement(int num) {\n int i = 0, res = 0;\n while(num > 0){\n // if last bit
logan138
NORMAL
2020-05-04T07:34:40.873819+00:00
2020-05-04T09:50:59.053991+00:00
366
false
```\n1st solution:-\n\nclass Solution {\n public int findComplement(int num) {\n int i = 0, res = 0;\n while(num > 0){\n // if last bit of num is 0, then we need to take complement of it\n // so, add corresponding pow to res.\n if((1 & num) == 0) res += Math.pow(2, i);\n i++;\n num = num >> 1;\n }\n return res;\n }\n}\n\n2nd solution:-\n// same logic as above solution. but different implementation\nclass Solution {\n public int findComplement(int num) {\n int power = 1, res = 0;\n while(num > 0){\n res += ((1 & num) ^ 1) * power;\n power <<= 1;\n num >>= 1;\n }\n return res;\n }\n}\n```\n**If you have any doubts, feel free to ask.\n if you understand, don\'t forget to upvote \u25C9\u203F\u25C9**
4
1
[]
0
number-complement
C++ SIMPLE EASY NAIVE SOLUTION
c-simple-easy-naive-solution-by-chase_ma-m3js
\nclass Solution {\npublic:\n int findComplement(int num) {\n \n int x =0;\n int d=0;\n string s="";\n while(num){\n
chase_master_kohli
NORMAL
2019-12-01T21:51:24.336651+00:00
2019-12-01T21:51:24.336683+00:00
184
false
```\nclass Solution {\npublic:\n int findComplement(int num) {\n \n int x =0;\n int d=0;\n string s="";\n while(num){\n s=to_string(num&1) +s;\n num/=2;\n }\n int i = 0;\n while(i<s.length()){\n s[i]=s[i]==\'1\'?\'0\':\'1\';\n i++;\n }\n i=s.length()-1;\n while(i>-1){\n x+=(s[i]-\'0\')*pow(2,d);\n i--;\n d++;\n }\n return x;\n \n }\n};\n```
4
0
[]
0
number-complement
Javascript
javascript-by-cuijingjing-pnu6
\nvar findComplement = function(num) {\n var number = num.toString(2);\n var str = \'\';\n for(let i of number) {\n str += +!(i-0);\n }\n
cuijingjing
NORMAL
2019-04-11T04:27:28.582821+00:00
2019-04-11T04:27:28.582850+00:00
278
false
```\nvar findComplement = function(num) {\n var number = num.toString(2);\n var str = \'\';\n for(let i of number) {\n str += +!(i-0);\n }\n return parseInt(str, 2)\n};\n```
4
0
[]
0
number-complement
Cpp O(lgN) solution
cpp-olgn-solution-by-calotte-1rf0
\nclass Solution {\npublic:\n int findComplement(int num) {\n long long t=1;\n while(t<=num)\n t=t<<1;\n return (t-1)^num;\n
calotte
NORMAL
2018-10-07T13:21:24.807657+00:00
2018-10-07T13:21:24.807696+00:00
290
false
```\nclass Solution {\npublic:\n int findComplement(int num) {\n long long t=1;\n while(t<=num)\n t=t<<1;\n return (t-1)^num;\n }\n};\n```
4
0
[]
3
number-complement
Trivial Ruby one-liner
trivial-ruby-one-liner-by-stefanpochmann-l7hv
\ndef find_complement(num)\n num.to_s(2).tr('01', '10').to_i(2)\nend\n
stefanpochmann
NORMAL
2017-01-08T11:56:55.365000+00:00
2017-01-08T11:56:55.365000+00:00
545
false
```\ndef find_complement(num)\n num.to_s(2).tr('01', '10').to_i(2)\nend\n```
4
0
[]
0
number-complement
JavaScript 1 line
javascript-1-line-by-samaritan89-32pl
\nvar findComplement = function(num) {\n return num ^ parseInt(num.toString(2).replace(/\\d/g, '1'), 2);\n};\n
samaritan89
NORMAL
2017-10-22T06:43:29.370000+00:00
2017-10-22T06:43:29.370000+00:00
494
false
```\nvar findComplement = function(num) {\n return num ^ parseInt(num.toString(2).replace(/\\d/g, '1'), 2);\n};\n```
4
1
['JavaScript']
0
the-number-of-full-rounds-you-have-played
C++ straightforward 3 lines
c-straightforward-3-lines-by-lzl124631x-6fea
See my latest update in repo LeetCode\n## Solution 1.\n\n1. Convert the startTime and finishTime into minutes.\n2. If startTime > finishTime, add 24 hours to fi
lzl124631x
NORMAL
2021-06-20T04:01:53.294063+00:00
2021-06-20T05:06:07.837552+00:00
5,348
false
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n## Solution 1.\n\n1. Convert the `startTime` and `finishTime` into minutes.\n2. If `startTime > finishTime`, add 24 hours to `finishTime` because we played overnight.\n3. Divide `startTime` and `finishTime` by 15, and round them UP and DOWN respectively. In this way we round the `startTime` and `endTime` to their next/previous closest 15-minute rounds, respectively. So `floor(finish / 15) - ceil(start / 15)` is number of rounds inbetween. \n\nNote that if `startTime` and `finishTime` are in the same 15-minute round, the above returns `-1`. We should return `max(0, floor(finish / 15) - ceil(start / 15))`\n\n```cpp\n// OJ: https://leetcode.com/contest/weekly-contest-246/problems/the-number-of-full-rounds-you-have-played/\n// Author: github.com/lzl124631x\n// Time: O(1)\n// Space: O(1)\nclass Solution {\npublic:\n int numberOfRounds(string s, string f) {\n int start = 60 * stoi(s.substr(0, 2)) + stoi(s.substr(3)), finish = 60 * stoi(f.substr(0, 2)) + stoi(f.substr(3));\n if (start > finish) finish += 60 * 24; // If `finishTime` is earlier than `startTime`, add 24 hours to `finishTime`.\n return max(0, finish / 15 - (start + 14) / 15); // max(0, floor(finish / 15) - ceil(start / 15))\n }\n};\n```
130
20
[]
17
the-number-of-full-rounds-you-have-played
Clean Java, O(1)
clean-java-o1-by-mardlucca-clg3
Well, at least I claim this is clean/readable: :-)\n\n\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n int star
mardlucca
NORMAL
2021-06-20T04:37:35.776861+00:00
2021-06-20T04:37:35.776891+00:00
2,635
false
Well, at least I claim this is clean/readable: :-)\n\n```\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n int start = toMinutes(startTime);\n int end = toMinutes(finishTime);\n \n int roundedStart = toNextQuarter(start);\n int roundedEnd = toPreviousQuarter(end);\n \n if (start < end) {\n return Math.max(0, (roundedEnd - roundedStart) / 15);\n }\n \n return (24 * 60 - roundedStart + roundedEnd) / 15;\n }\n \n public static int toMinutes(String s) {\n return Integer.parseInt(s.substring(0, 2)) * 60\n + Integer.parseInt(s.substring(3, 5));\n }\n \n public static int toNextQuarter(int time) {\n return ((time + 14) / 15) * 15;\n }\n\n public static int toPreviousQuarter(int time) {\n return (time / 15) * 15;\n }\n}\n```\n
47
0
[]
4
the-number-of-full-rounds-you-have-played
[Python3] math-ish
python3-math-ish-by-ye15-gmgr
\n\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n hs, ms = (int(x) for x in startTime.split(":"))\n ts
ye15
NORMAL
2021-06-20T04:03:26.635656+00:00
2021-06-20T22:20:59.174635+00:00
2,371
false
\n```\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n hs, ms = (int(x) for x in startTime.split(":"))\n ts = 60 * hs + ms\n hf, mf = (int(x) for x in finishTime.split(":"))\n tf = 60 * hf + mf\n if 0 <= tf - ts < 15: return 0 # edge case \n return tf//15 - (ts+14)//15 + (ts>tf)*96\n```\n\n```\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n ts = 60 * int(startTime[:2]) + int(startTime[-2:])\n tf = 60 * int(finishTime[:2]) + int(finishTime[-2:])\n if 0 <= tf - ts < 15: return 0 # edge case \n return tf//15 - (ts+14)//15 + (ts>tf)*96\n```
23
2
['Python3']
5
the-number-of-full-rounds-you-have-played
c++ easy with explained solution Passing all Edge CASES
c-easy-with-explained-solution-passing-a-gieu
1. To handle the case where our startTime is greater then endTime we add a period of 24 hrs ie 24*60.\n2. To handle the case were startTime must be in the range
super_cool123
NORMAL
2021-06-20T05:33:39.817645+00:00
2021-06-27T10:16:19.275040+00:00
1,414
false
**1. To handle the case where our startTime is greater then endTime we add a period of 24 hrs ie 24*60.\n2. To handle the case were startTime must be in the range of [15:30:45:60] we can add 14 to start time in that way we can skip [0 to 14] time interval\n3. To Handle the edge case we have to convert the time to minute by multiplying by 60 sec.**\n```\nclass Solution {\n public:\n int numberOfRounds(string s, string f) {\n \n\t\tint startT = 60 * stoi(s.substr(0,2)) + stoi(s.substr(3));\n\t\tint finishT = 60 * stoi(f.substr(0,2)) + stoi(f.substr(3));\n\n\t\tif (startT > finishT)\n\t\t\tfinishT += 24 * 60;\n\n\t\treturn max(0, (finishT / 15) - (startT + 14) / 15);\n \n }\n};\n```
16
4
['C']
4
the-number-of-full-rounds-you-have-played
Java O(1) 100% faster
java-o1-100-faster-by-akhil_t-6t5j
\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n Integer startHH = Integer.parseInt(startTime.substring(0,2));\
akhil_t
NORMAL
2021-06-20T05:23:23.167738+00:00
2021-06-20T05:23:23.167767+00:00
1,813
false
```\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n Integer startHH = Integer.parseInt(startTime.substring(0,2));\n Integer startMM = Integer.parseInt(startTime.substring(3));\n Integer finishHH = Integer.parseInt(finishTime.substring(0,2));\n Integer finishMM = Integer.parseInt(finishTime.substring(3));\n \n int start = startHH*60 +startMM;\n int end = finishHH*60 +finishMM;\n if (start > end) {\n end += 24*60;\n }\n \n return (int) Math.floor(end / 15.00) - (int) Math.ceil(start / 15.00);\n }\n}\n```
14
1
['Java']
7
the-number-of-full-rounds-you-have-played
Clean Python 3, straightforward
clean-python-3-straightforward-by-lenche-znah
Time: O(1)\nSpace: O(1)\n\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n if finishTime < startTime:\n
lenchen1112
NORMAL
2021-06-20T04:03:23.751976+00:00
2021-06-21T06:17:25.830323+00:00
1,101
false
Time: `O(1)`\nSpace: `O(1)`\n```\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n if finishTime < startTime:\n return self.numberOfRounds(startTime, \'24:00\') + self.numberOfRounds(\'00:00\', finishTime)\n sHH, sMM = map(int, startTime.split(\':\'))\n fHH, fMM = map(int, finishTime.split(\':\'))\n start = sHH * 60 + sMM\n finish = fHH * 60 + fMM\n return max(0, finish // 15 - (start // 15 + (start % 15 > 0))) # thanks migeater for the case 12:01 - 12:02\n```
12
0
[]
5
the-number-of-full-rounds-you-have-played
Very simple C++ solution
very-simple-c-solution-by-hc167-mq0o
Updated solution to preserve the original logic as much as possible,\n\n\nclass Solution {\npublic:\n int numberOfRounds(string startTime, string finishTime)
hc167
NORMAL
2021-06-20T04:01:13.223670+00:00
2021-06-27T14:23:27.634773+00:00
1,184
false
Updated solution to preserve the original logic as much as possible,\n\n```\nclass Solution {\npublic:\n int numberOfRounds(string startTime, string finishTime) {\n int a = stoi(startTime.substr(0, 2));\n int b = stoi(startTime.substr(3, 2));\n int c = stoi(finishTime.substr(0, 2));\n int d = stoi(finishTime.substr(3, 2));\n \n a = a*60+b;\n c = c*60+d;\n\n if(c < a)\n c += 60*24;\n \n if(a%15 != 0)\n a += (15-(a%15));\n if(c%15 != 0)\n c -= (c%15);\n \n int val = (c-a)/15;\n return max(0, val);\n }\n};\n\n```
11
4
[]
5
the-number-of-full-rounds-you-have-played
Java O(1)
java-o1-by-vikrant_pc-9ba1
\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n int[] start = getTime(startTime), end = getTime(finishTime);\n
vikrant_pc
NORMAL
2021-06-20T04:00:43.429775+00:00
2021-06-20T04:00:43.429813+00:00
544
false
```\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n int[] start = getTime(startTime), end = getTime(finishTime);\n if(end[0] < start[0] || end[0] == start[0] && end[1] < start[1]) end[0] += 24; // Midnight case\n return (end[0] * 4 + end[1]/15) - (start[0] * 4 + ((int)Math.ceil((double)start[1]/15)));\n }\n private int[] getTime(String t) {\n return new int[] {(t.charAt(0) - \'0\') * 10 + (t.charAt(1) - \'0\'), (t.charAt(3) - \'0\') * 10 + (t.charAt(4) - \'0\')};\n }\n}\n```
8
6
[]
3
the-number-of-full-rounds-you-have-played
Python: Brute-force: Constant Time and Space.
python-brute-force-constant-time-and-spa-geh1
Idea: Split the time into hours and minutes.\n\nif start hour == end hour, and start min < end min, this simply means start time is less than end time.\nso, get
meaditya70
NORMAL
2021-06-20T04:23:40.144856+00:00
2021-06-20T04:25:41.471679+00:00
604
false
Idea: Split the time into hours and minutes.\n\nif start hour == end hour, and start min < end min, this simply means start time is less than end time.\nso, get the difference between the number of games he/she can play witin that time. \nNote: if start min = 1 and end min = 46, then our games played will be only 2 from 15-30 min and 30 - 45 min.\nSo, **do not do (end min - start min)//15** because it will give you (46-1)//15 = 3 which is not true.\n\nSo, just take care of such things and it can be solved easily.\n\nI guess the code is self explanatory. Kindly go through it. Incase of any doubts, feel free to comment down below.\n\nHave a great day!\n\n```\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n sh, sm = startTime.split(":")\n eh, em = finishTime.split(":")\n\t\t\n # sh - hour part of the start time\n\t\t# sm - minute part of the start time\n\t\t# eh - hour part of the finish time\n\t\t# em = minute part of the finish time\n sh, sm, eh, em = int(sh), int(sm), int(eh), int(em)\n \n if sh == eh:\n if sm <= em:\n return em//15 - (sm//15 + 1)\n else:\n val = 0\n sm = 60 - sm\n val += sm//15\n val += em//15\n return 23*4 + val \n else:\n if eh < sh:\n eh += 24\n val = 0\n sm = 60 - sm\n val += sm//15\n val += em//15\n sh += 1\n return (eh-sh)*4 + val\n```\nTime = Space = O(1)
6
2
['Python']
2
the-number-of-full-rounds-you-have-played
JS Solution, Date function
js-solution-date-function-by-chejianchao-paad
\nuse ceil to get the valid start time.\n\nvar numberOfRounds = function(startTime, finishTime) {\n var s = new Date(`2020-01-01T${startTime}:00Z`);\n var
chejianchao
NORMAL
2021-06-20T04:01:50.027843+00:00
2021-06-20T04:01:50.027877+00:00
473
false
\nuse ceil to get the valid start time.\n```\nvar numberOfRounds = function(startTime, finishTime) {\n var s = new Date(`2020-01-01T${startTime}:00Z`);\n var e;\n if(finishTime < startTime)\n e = new Date(`2020-01-02T${finishTime}:00Z`);\n else\n e = new Date(`2020-01-01T${finishTime}:00Z`);\n var st = Math.ceil(s.getTime() / 15 / 60000) * 15 * 60000;\n return Math.floor((e.getTime() - st) / (15 * 60000));\n};\n```
6
0
[]
2
the-number-of-full-rounds-you-have-played
Java Super simple sol
java-super-simple-sol-by-sting__112-ow9p
\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n int start = timeInMinute(startTime); //convert start time to m
sting__112
NORMAL
2021-06-20T05:22:11.700949+00:00
2021-06-20T05:22:25.260507+00:00
651
false
```\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n int start = timeInMinute(startTime); //convert start time to minutes\n int end = timeInMinute(finishTime); //Convert end time to minutes\n \n if(end < start)\n end += 24*60;\n \n if(start % 15 != 0)\n start += 15 - (start % 15); // make the starting point from the multiple of 15\n \n if(end % 15 != 0)\n end -= end % 15; // make the ending point multiple of 15\n \n if(end < start)\n return 0;\n \n return (end-start)/15;\n \n }\n \n private int timeInMinute(String s){\n int h = Integer.parseInt(s.substring(0,2));\n int m = Integer.parseInt(s.substring(3));\n \n return (h*60)+m;\n }\n}\n```
5
0
['Java']
0
the-number-of-full-rounds-you-have-played
Java O(1) solution with comments in the code for better understanding
java-o1-solution-with-comments-in-the-co-vgv5
Here we\'re basically converting the startTime and endTime to minutes and then calculating then result.\n\nclass Solution {\n public int numberOfRounds(Strin
fresh_avocado
NORMAL
2021-06-20T05:09:28.433482+00:00
2021-06-20T05:09:28.433514+00:00
422
false
Here we\'re basically converting the startTime and endTime to minutes and then calculating then result.\n```\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n \n int finMin = Integer.parseInt(finishTime.substring(3, 5));\n int startMin = Integer.parseInt(startTime.substring(3,5));\n int finHr = Integer.parseInt(finishTime.substring(0, 2));\n int startHr = Integer.parseInt(startTime.substring(0, 2));\n \n int start = startHr * 60 + startMin; //converting start time to minutes\n int end = finHr * 60 + finMin; // converting endtime to minutes\n \n if(start % 15 != 0) { // making start to next multiple of 15 \n int div = start/15; // doing this because in start time for example of 03:10(190 mins), \n start = 15 * (div + 1); //we can join the contest at 03:15(195 mins) only and 195 is next multiple of 15 after 190.\n }\n \n if(end % 15 != 0) { //doing the same here but instead of finding the next multiple we\'re rounding off to previous multiple of 15\n int div = end/15; // as ending time of for example 03:10 we have to count till 03:00 because at 03:00 new game starts\n end = 15 * div; // but it ends at 03:15 but our end time is 03:10\n }\n \n if(end < start) end = end + 24*60; //here if ending time < start time. see example 2 of the provided test cases.\n // basically the game ends at next day so we added 24 more hours\n \n \n return Math.abs(end - start) / 15; // now to find the number of games played we divide the time difference by 15\n }\n}\n```
5
0
['Java']
1
the-number-of-full-rounds-you-have-played
[Python] play with Numbers
python-play-with-numbers-by-vegishanmukh-blda
The main idea behind this solution was :\n1.Convert times to numbers\n2.Find the first time where a play can start\n3.If the end time is less than start, go on
vegishanmukh7
NORMAL
2021-06-20T04:40:37.167311+00:00
2021-06-20T04:40:37.167341+00:00
604
false
The main idea behind this solution was :\n1.Convert times to numbers\n2.Find the first time where a play can start\n3.If the end time is less than start, go on untill 2400 and make start-index to 0\n3.Go on untill we reach the end time\n\nThe main point to be remembered here is 10:60 is treated same as 11:00.\n~~~\nclass Solution:\n def numberOfRounds(self, s: str, f: str) -> int:\n si=int(s[:2]+s[3:]) #start integer\n ei=int(f[:2]+f[3:]) #end integer\n while((si%100)%15!=0):si+=1 #if last two digits are divisible by 15 then it\'s start time\n count=0\n if(ei<si): #end integer is less than start integer\n while(si<=2360): #if end time is less than start time\n\t\t#if we reached a perfect hour we need to go to next hour + 15\n\t\t#that is if we are at 10:60 and if we add 40 we go to 11:00 but 11:00 is same as 10:60, \n\t\t#so increment by another 15 = 40+15=55\n if((si%100)==60):si+=55 \n else:si+=15 #increment time by 15 minutes indicating completion of a time slot\n count+=1\n count-=1 #As we moved one step ahead(<=2360) decrementing the count\n si=0 #setting start time as 0\n while(si<=ei):\n count+=1\n if((si%100)==60):si+=55 #same above logic applies here\n else:si+=15\n count-=1\n return count\n~~~
5
1
[]
0
the-number-of-full-rounds-you-have-played
Easy O(1) C++ solution with explanation.
easy-o1-c-solution-with-explanation-by-r-490l
Consider the testcase startTime = \'12:01\' and finishTIme = \'13:44\'\n\n\n ceil floor \n |-> <-|\n\t|---|---|--
r-aravind
NORMAL
2021-06-21T04:28:06.110106+00:00
2021-06-21T04:28:40.969841+00:00
346
false
Consider the testcase `startTime = \'12:01\'` and `finishTIme = \'13:44\'`\n\n```\n ceil floor \n |-> <-|\n\t|---|---|---|---|---|---|---|---|\n\t| | |\n\t12:00 13:00 14:00\n```\n\n\n\nSolution:\n- Convert `startTime` and `finishTime` to minutes\n\n- find the ceil of `startTime` to get the beginning of the first round.\n\n `(start + 14) / 15)` \n Here we add 14 to get to the first round played.\n `HH:00`, `HH:15`, `HH:30` and `HH:45` will stay in the same round while all other cases will skip the incomplete first round.\n\n- find the floor of `finishTime` to get the end of the last round in the given range.\n\n\t`(finish / 15)`\n\n- Their difference gives the number of rounds played.\n\n\n\nSubmission:\n\n```\nclass Solution {\n public:\n int numberOfRounds(string s, string f) {\n \n\t\tint start = 60 * stoi(s.substr(0,2)) + stoi(s.substr(3));\n\t\tint finish = 60 * stoi(f.substr(0,2)) + stoi(f.substr(3));\n\n\t\tif (start > finish)\n\t\t\tfinish += 24 * 60;\n\n\t\treturn max(0, (finish / 15) - (start + 14) / 15);\n \n }\n };\n```\n
4
0
[]
0
the-number-of-full-rounds-you-have-played
[C++] | With comments & Examples | O(1) | 100% Faster
c-with-comments-examples-o1-100-faster-b-dfn8
Handling just 2 cases takes care of every corner case. And by seeing some common parts in code and, you can make code shorter ,but I think its easy to understan
7ravip
NORMAL
2021-06-20T04:24:38.851670+00:00
2021-06-23T02:40:36.115817+00:00
340
false
#### Handling just 2 cases takes care of every corner case. And by seeing some common parts in code and, you can make code shorter ,but I think its easy to understand this way\n```\nclass Solution {\npublic:\n int numberOfRounds(string s, string f) {\n\t\t//Just Some preprocessing :-/\n int sh = (s[0]-\'0\')*10 + (s[1]-\'0\'); //start hour\n double sm = (s[3]-\'0\')*10 + (s[4]-\'0\'); //start minute\n int fh = (f[0]-\'0\')*10 + (f[1]-\'0\'); //final hour\n double fm = (f[3]-\'0\')*10 + (f[4]-\'0\'); //final minute\n \n\t\t//changing the minutes bounds \n sm = ceil(sm/15) * 15; // for 12:01 it will become 12:15\n fm = floor(fm/15) *15; // for 14:07 it will become 14:00\n int ret = 0;\n\t\t\n\t\t//preprocessing ends\n\t\t//condition of finish time higher than start time\n if(fh>sh || (fh == sh && fm>=sm)){\n if(fh == sh){ \n // for 12:01(scales up to 12:15) - 12:44(scaled downto 12:30) return (30 -15)/15;\n return (fm -sm)/15; \n }\n // for 12:05 {==> 12:15} - 14:22 {==> 14:15 } \n \n ret = ret + 4*(fh-(sh+1)); // calculate from (14 to 12+1)\n ret = ret + (60-sm)/15 + fm/15; // add minutes from 12:15 - 13:00 && 14:00 - 14:15\n }\n else{\n // ex : 20:15 - 6:42 { becomes 6:30}\n // add hours from 20:00 - 24:00 (added extra round 20:00 - 20:15 , so have to substract it)\n //add hours from 24:00 - 6:00 \n ret = ret + 4*(24 - sh) + 4*fh;\n \n //substracting the extra round and adding extra round from 6:00 - 6:30\n ret = ret - (sm)/15 + fm/15;\n \n }\n return ret;\n }\n};\n```
4
1
[]
0
the-number-of-full-rounds-you-have-played
C++ no bullshit
c-no-bullshit-by-rajat2105-nde8
JUST CHECK IF FINISH TIME IS MULTIPLE OF 15.TAKES CARE OF ALL CASES\n```\nclass Solution {\npublic:\n int numberOfRounds(string st, string ft) {\n int
rajat2105
NORMAL
2021-06-20T04:11:09.696701+00:00
2021-07-29T17:41:53.453747+00:00
282
false
JUST CHECK IF FINISH TIME IS MULTIPLE OF 15.TAKES CARE OF ALL CASES\n```\nclass Solution {\npublic:\n int numberOfRounds(string st, string ft) {\n int s=0;\n s=(st[0]-\'0\')*1000+(st[1]-\'0\')*100+(st[3]-\'0\')*10+st[4]-\'0\';\n int f=0;\n f=(ft[0]-\'0\')*1000+(ft[1]-\'0\')*100+(ft[3]-\'0\')*10+ft[4]-\'0\';\n int ans=0;\n if(((f%100)%15)==0)ans++;\n while(s!=f)\n {\n \n if(((s%100)%15)==0)\n ans++;\n if((s%100)==59)\n {\n s=s/100;\n if(s==23)s=0;\n else{\n s++;\n s=s*100;\n }\n }\n else\n s++;\n }\n return ans-1;\n }\n};
4
0
[]
0
the-number-of-full-rounds-you-have-played
[C++] Simple C++ Code || O(1) time
c-simple-c-code-o1-time-by-prosenjitkund-sczp
\n# If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.\n\nclass Solution {\npubli
_pros_
NORMAL
2022-09-02T15:49:31.934256+00:00
2022-09-02T15:49:31.934352+00:00
369
false
\n# **If you like the implementation then Please help me by increasing my reputation. By clicking the up arrow on the left of my image.**\n```\nclass Solution {\npublic:\n int numberOfRounds(string loginTime, string logoutTime) {\n int INtime = ((loginTime[0]-\'0\')*10+loginTime[1]-\'0\')*60 + (loginTime[3]-\'0\')*10+loginTime[4]-\'0\';\n int OUTtime = ((logoutTime[0]-\'0\')*10+logoutTime[1]-\'0\')*60 + (logoutTime[3]-\'0\')*10+logoutTime[4]-\'0\';\n if(OUTtime < INtime)\n {\n OUTtime += 1440;\n }\n if(INtime%15 != 0)\n {\n int val = INtime/15;\n INtime = (val+1)*15; \n }\n return abs(OUTtime-INtime)/15;\n }\n};\n```
3
0
['Math', 'C', 'C++']
0
the-number-of-full-rounds-you-have-played
Java | Simple | Easy to understand
java-simple-easy-to-understand-by-phani_-0j5v
```\nclass Solution {\n public int numberOfRounds(String loginTime, String logoutTime) {\n String[] arr1 = loginTime.split(":");\n String[] arr
phani_java
NORMAL
2022-03-25T07:01:28.296387+00:00
2022-03-25T07:01:28.296425+00:00
497
false
```\nclass Solution {\n public int numberOfRounds(String loginTime, String logoutTime) {\n String[] arr1 = loginTime.split(":");\n String[] arr2 = logoutTime.split(":"); \n \n int time1 = Integer.parseInt(arr1[0])*60 + Integer.parseInt(arr1[1]);\n int time2 = Integer.parseInt(arr2[0])*60 + Integer.parseInt(arr2[1]);\n\n if(time1 > time2) time2 = time2 + 24*60;\n if(time1%15 != 0) time1 = time1 + 15-time1%15;\n \n return (time2 - time1)/15;\n }\n}
3
0
['Java']
0
the-number-of-full-rounds-you-have-played
[Python] 7 lines (simple!)
python-7-lines-simple-by-m-just-bu9v
python\ndef numberOfRounds(self, startTime: str, finishTime: str) -> int:\n s = int(startTime[:2]) * 60 + int(startTime[-2:])\n t = int(finishTime[:2]) *
m-just
NORMAL
2021-06-22T14:20:49.362783+00:00
2021-06-22T14:22:48.265225+00:00
448
false
```python\ndef numberOfRounds(self, startTime: str, finishTime: str) -> int:\n s = int(startTime[:2]) * 60 + int(startTime[-2:])\n t = int(finishTime[:2]) * 60 + int(finishTime[-2:])\n if s > t:\n t += 24 * 60\n q, r = divmod(s, 15)\n s, t = q + int(r > 0), t // 15\n return max(0, t - s)\n```\nVote up if you find this helpful, thanks!
3
1
['Python']
2
the-number-of-full-rounds-you-have-played
JAVA solution with visual explanation
java-solution-with-visual-explanation-by-vqxx
```\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n // think of a day as units of time, each unit consists 15 m
thaliah
NORMAL
2021-06-20T17:15:36.367752+00:00
2021-06-20T17:25:09.346050+00:00
135
false
```\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n // think of a day as units of time, each unit consists 15 minutes \n // so within a day, there will be 24 * 4 = 96 units (4 15-min units per hour)\n\n // 0----15min----1----15min----2----15min----3----15min----4 \n \n // re-represent the statTime and endTime using this new unit of time, \n // the number of units between them will be the number of full rounds one can play\n \n // 0--------1--------2--------3--------4 \n // ^ ^ 2 units in between\n // start end\n \n // 0--------1--------2--------3--------4 \n // ^ ^ 3 units in between\n // start end\n \n // 0--------1--------2--------3--------4 \n // ^ ^ 4 units in between\n // start end\n \n int startH = Integer.parseInt(startTime.substring(0, 2));\n int startM = Integer.parseInt(startTime.substring(3));\n int endH = Integer.parseInt(finishTime.substring(0, 2));\n int endM = Integer.parseInt(finishTime.substring(3));\n \n int start = startH * 60 + startM;\n int end = endH * 60 + endM;\n \n // when start > end (play overnight), we can simply shift the end time by 24 hours\n \n // 0--------1--------2--------3--------4 \n // ^ ^ \n // end start\n \n // 0--------1--------2--------3--------4-------...... 96--------97 \n // ^ end of day1 ^ \n // start end\n \n if (start > end) end += 24 * 60;\n \n return (int) (Math.floor(end / 15f) - Math.ceil(start / 15f));\n \n }\n}
3
1
['Java']
0
the-number-of-full-rounds-you-have-played
Very easy method C++
very-easy-method-c-by-kaspil-2fh3
class Solution {\npublic:\n \n int numberOfRounds(string s, string f) {\n int h1,h2,m1,m2;\n h1=(s[0]-\'0\')10+(s[1]-\'0\');\n m1=(s[3]
kaspil
NORMAL
2021-06-20T08:20:33.399065+00:00
2021-06-20T08:20:33.399108+00:00
229
false
class Solution {\npublic:\n \n int numberOfRounds(string s, string f) {\n int h1,h2,m1,m2;\n h1=(s[0]-\'0\')*10+(s[1]-\'0\');\n m1=(s[3]-\'0\')*10+(s[4]-\'0\');\n h2=(f[0]-\'0\')*10+(f[1]-\'0\');\n m2=(f[3]-\'0\')*10+(f[4]-\'0\');\n int cnt=0,cnt1=0,hh=0;\n if(h2>=h1){\n hh=abs(h1-h2);\n }\n else{\n hh=h2+24-h1;\n }\n if(m1%15==0)\n cnt=m1/15;\n else\n cnt=(m1/15)+1;\n cnt1=m2/15;\n int ans=hh*4+(cnt1-cnt);\n if(ans<0)\n ans+=96;\n return ans;\n }\n};
3
0
[]
2
the-number-of-full-rounds-you-have-played
O(1) time complexity, easy to understand, 2 solutions
o1-time-complexity-easy-to-understand-2-n7rrl
O(1) time complexity and O(1) space complexity\ncode is self explanatory. Kindly go through it. Incase of any doubts, feel free to comment.\n\n\nclass Solution:
code-fanatic
NORMAL
2021-06-20T04:22:26.781947+00:00
2021-06-20T06:46:01.035902+00:00
361
false
O(1) time complexity and O(1) space complexity\ncode is self explanatory. Kindly go through it. Incase of any doubts, feel free to comment.\n\n```\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n\n start=startTime.split(":")\n startHour,startMin=int(start[0]),int(start[1])\n \n end=finishTime.split(":")\n endHour,endMin=int(end[0]),int(end[1])\n # if start time is greater than endtime, calculate round till 00:00 and then till finish time\n if (startHour>endHour ) or (startHour==endHour and startMin >endMin):\n return (24-startHour-1)*4+(60-startMin)//15 +self.numberOfRounds("00:00",finishTime)\n else:\n if startMin not in [0,15,30,45]:\n if startMin<15:startMin=15\n elif startMin<30:startMin=30\n elif startMin<45:startMin=45\n elif startHour!=23:\n startMin=0\n startHour+=1\n else:\n startMin=0\n startHour=0\n\n if endHour==startHour:return (endMin-startMin)//15\n else:\n return (endHour-startHour)*4+(endMin-startMin)//15\n \n```\nSolution 2\n```\nstart=startTime.split(":")\n startHour,startMin=int(start[0]),int(start[1])\n startTotalMins=startHour*60+startMin\n \n end=finishTime.split(":")\n endHour,endMin=int(end[0]),int(end[1])\n endTotalMins=endHour*60+endMin\n\t\t# adding 14 in startMins to neglect rounds which started just after 0,15,30,45 mins\n\t\t# for example "00:01" "00:44" => 44//15-(01+14)//15+0==1\n\t\t# if we don\'t add 14 then round starting from 1 will also be calculated \n return endTotalMins//15-(startTotalMins+14)//15 + (startTotalMins>endTotalMins)*96\n```
3
1
['Math', 'Python', 'Python3']
1
the-number-of-full-rounds-you-have-played
Two Tricks
two-tricks-by-votrubac-5nr7
Check if the end time is tomorrow.\n2. Round the start time up to 15-minute mark, and round the end time down.\n\nC++\ncpp\nint numberOfRounds(string a, string
votrubac
NORMAL
2021-06-20T04:03:30.792323+00:00
2021-06-22T17:17:37.354515+00:00
381
false
1. Check if the end time is tomorrow.\n2. Round the start time up to 15-minute mark, and round the end time down.\n\n**C++**\n```cpp\nint numberOfRounds(string a, string b) {\n auto nn = [](const string &s, int i){ \n return (s[i] - \'0\') * 10 + s[i + 1] - \'0\'; };\n int m1 = nn(a, 0) * 60 + nn(a, 3), m2 = nn(b, 0) * 60 + nn(b, 3);\n if (m2 < m1)\n m2 += 24 * 60;\n return max(0, (m2 / 15) - (m1 + 14) / 15);\n}\n```
3
1
['C']
0
the-number-of-full-rounds-you-have-played
[Python + Java] (Convert to minutes)
python-java-convert-to-minutes-by-m0u1ea-m267
Python\npython\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n def convert(s):\n return int(s[:2])*6
M0u1ea5
NORMAL
2021-06-20T04:02:42.801207+00:00
2021-06-22T15:22:21.714217+00:00
219
false
**Python**\n```python\nclass Solution:\n def numberOfRounds(self, startTime: str, finishTime: str) -> int:\n def convert(s):\n return int(s[:2])*60+int(s[3:])\n \n st = convert(startTime)\n ft = convert(finishTime)\n \n if ft < st:\n ft += 1440\n \n if st % 15 != 0:\n st += 15-(st%15)\n \n return int((ft-st)/15)\n\n```\n---\n\n**Java**\n```java\nclass Solution {\n int convert(String s){\n String[] ss = s.split(":");\n return (Integer.parseInt(ss[0])*60) + (Integer.parseInt(ss[1]));\n }\n \n public int numberOfRounds(String startTime, String finishTime) {\n int st = convert(startTime);\n int ft =convert(finishTime);\n \n if (ft < st){\n ft += 1440;\n }\n if (st % 15 != 0){\n st += (15-st%15);\n }\n return (ft-st)/15;\n \n }\n}\n\n```
3
0
[]
1
the-number-of-full-rounds-you-have-played
C# simple solution
c-simple-solution-by-bykarelin-x8q5
Complexity\n- Time complexity:\no(1)\n\n- Space complexity:\no(1)\n\n# Code\n\npublic class Solution {\n public int NumberOfRounds(string loginTime, string l
bykarelin
NORMAL
2022-11-21T18:41:25.145514+00:00
2022-11-21T18:41:25.145545+00:00
91
false
# Complexity\n- Time complexity:\n$$o(1)$$\n\n- Space complexity:\n$$o(1)$$\n\n# Code\n```\npublic class Solution {\n public int NumberOfRounds(string loginTime, string logoutTime) {\n var t1 = ToInt(loginTime);\n var t2 = ToInt(logoutTime);\n if (t2 < t1)\n t2 += 60*24;\n if (t1%15 != 0)\n t1 += 15-t1%15;\n if (t2 % 15 != 0)\n t2 = (t2/15) * 15;\n if (t1 > t2)\n return 0;\n return (t2-t1) / 15;\n }\n\n private int ToInt(string time) {\n var sp = time.Split(":");\n return int.Parse(sp[0]) * 60 + int.Parse(sp[1]);\n }\n}\n```
2
0
['C#']
0
the-number-of-full-rounds-you-have-played
c++ | easy | short
c-easy-short-by-venomhighs7-2n7y
\n\n# Code\n\nclass Solution {\npublic:\n int numberOfRounds(string loginTime, string logoutTime) {\n int INtime = ((loginTime[0]-\'0\')*10+loginTime[
venomhighs7
NORMAL
2022-11-03T03:52:10.948931+00:00
2022-11-03T03:52:10.948977+00:00
409
false
\n\n# Code\n```\nclass Solution {\npublic:\n int numberOfRounds(string loginTime, string logoutTime) {\n int INtime = ((loginTime[0]-\'0\')*10+loginTime[1]-\'0\')*60 + (loginTime[3]-\'0\')*10+loginTime[4]-\'0\';\n int OUTtime = ((logoutTime[0]-\'0\')*10+logoutTime[1]-\'0\')*60 + (logoutTime[3]-\'0\')*10+logoutTime[4]-\'0\';\n if(OUTtime < INtime)\n {\n OUTtime += 1440;\n }\n if(INtime%15 != 0)\n {\n int val = INtime/15;\n INtime = (val+1)*15; \n }\n return abs(OUTtime-INtime)/15;\n }\n};\n```
2
0
['C++']
0
the-number-of-full-rounds-you-have-played
c++ | taking care for first and last hour , remaining hours contribute 4
c-taking-care-for-first-and-last-hour-re-t1pv
\nclass Solution {\npublic:\n int first(int m){\n if(m>45)return 0;\n if(m>30)return 1;\n if(m>15)return 2;\n if(m>0)return 3;\n
vishwasgajawada
NORMAL
2021-06-20T04:56:12.771246+00:00
2021-06-25T11:07:56.161605+00:00
103
false
```\nclass Solution {\npublic:\n int first(int m){\n if(m>45)return 0;\n if(m>30)return 1;\n if(m>15)return 2;\n if(m>0)return 3;\n return 4;\n }\n int last(int m){\n if(m<15)return 0;\n if(m<30)return 1;\n if(m<45)return 2;\n if(m<60)return 3;\n return 4;\n }\n int numberOfRounds(string st, string ft) {\n int h1 = (st[0]-\'0\')*10+(st[1]-\'0\');\n int m1 = (st[3]-\'0\')*10+(st[4]-\'0\');\n \n int h2 = (ft[0]-\'0\')*10+(ft[1]-\'0\');\n int m2 = (ft[3]-\'0\')*10+(ft[4]-\'0\');\n \n int ans = 0;\n if(h1>h2 || (h1==h2 && m1>m2)){\n h2 = (h2+24);\n }\n if(h2>h1){\n ans = (h2-h1-1)*4;\n ans+=first(m1)+last(m2);\n }else{\n if(m1 <= 0 && m2 >= 15)ans++;\n if(m1 <= 15 && m2 >= 30)ans++;\n if(m1 <= 30 && m2 >= 45)ans++;\n }\n return ans;\n }\n};\n```
2
2
['C', 'C++']
1
the-number-of-full-rounds-you-have-played
c++ Intuitive Solution
c-intuitive-solution-by-yam_malla-n17m
\n```\nclass Solution {\npublic:\n int numberOfRounds(string startTime, string finishTime) {\n int res = 0;\n int h1, m1, h2, m2;\n h1 =
yam_malla
NORMAL
2021-06-20T04:36:27.020860+00:00
2021-06-20T04:36:48.698424+00:00
79
false
\n```\nclass Solution {\npublic:\n int numberOfRounds(string startTime, string finishTime) {\n int res = 0;\n int h1, m1, h2, m2;\n h1 = stoi(startTime.substr(0,2));\n m1 = stoi(startTime.substr(3));\n \n h2 = stoi(finishTime.substr(0,2));\n m2 = stoi(finishTime.substr(3));\n res = (h2 - h1) * 4 - ((m1 + 14) /15) + (m2 /15) ;\n return (res + 96)%96;\n }\n};
2
1
[]
0
the-number-of-full-rounds-you-have-played
4 Lines Javascript Solution
4-lines-javascript-solution-by-ashish132-49f2
\nJavaScript 0(1) Solution\n\n\n\n\n\nvar numberOfRounds = function(startTime, finishTime) {\n var start=60*parseInt(startTime.slice(0,2))+parseInt(startTime
Ashish1323
NORMAL
2021-06-20T04:20:40.585661+00:00
2021-06-20T04:20:40.585687+00:00
250
false
\n**JavaScript 0(1) Solution**\n\n\n![image](https://assets.leetcode.com/users/images/64b3fd37-bc2b-43cc-a0bf-b63ee7f31876_1624162827.384518.png)\n\n```\nvar numberOfRounds = function(startTime, finishTime) {\n var start=60*parseInt(startTime.slice(0,2))+parseInt(startTime.slice(3))\n var end=60*parseInt(finishTime.slice(0,2))+parseInt(finishTime.slice(3))\n if(start>end) end+=24*60\n return Math.floor(end/15) - Math.ceil(start/15)\n};\n```
2
1
['Math', 'JavaScript']
3
the-number-of-full-rounds-you-have-played
Meaningful variable names | Easy to understand | straightforward and clean | Java
meaningful-variable-names-easy-to-unders-f5nj
\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n int startHour = Integer.parseInt(startTime.substring(0, 2));\n
cool_leetcoder
NORMAL
2021-06-20T04:12:35.622574+00:00
2021-06-20T04:13:42.900552+00:00
82
false
```\nclass Solution {\n public int numberOfRounds(String startTime, String finishTime) {\n int startHour = Integer.parseInt(startTime.substring(0, 2));\n int startMinute = Integer.parseInt(startTime.substring(3, 5));\n\n\n int finishHour = Integer.parseInt(finishTime.substring(0, 2));\n int finishMinute = Integer.parseInt(finishTime.substring(3, 5));\n\n if (finishHour < startHour || finishHour == startHour && finishMinute < startMinute) {\n finishHour += 24;\n }\n int startCount = (int)Math.ceil(startMinute / 15.0);\n int finishCount = (int)Math.floor(finishMinute / 15.0);\n return Math.max(0, finishHour * 4 + finishCount - (startHour * 4 + startCount));\n }\n}\n```
2
1
[]
1
the-number-of-full-rounds-you-have-played
Simple math solution
simple-math-solution-by-rohity821-imyo
Code
rohity821
NORMAL
2025-01-08T05:07:52.971804+00:00
2025-01-08T05:07:52.971804+00:00
29
false
# Code ```swift [] class Solution { func convertTimeStringToMinutes(_ timeString: String) -> Int { let split = timeString.split(separator: ":") return (Int(split[0]) ?? 0) * 60 + (Int(split[1]) ?? 0) } func numberOfRounds(_ loginTime: String, _ logoutTime: String) -> Int { var start = convertTimeStringToMinutes(loginTime), end = convertTimeStringToMinutes(logoutTime) // following this from question - If logoutTime is earlier than loginTime, // this means you have played from loginTime to midnight and from midnight to logoutTime. if end < start { end += 24 * 60 } var ans = 0 for time in start...end where time % 15 == 0 && end-time >= 15 { ans += 1 } return ans } } ```
1
0
['Math', 'String', 'Swift']
0
the-number-of-full-rounds-you-have-played
Easy solution to understand
easy-solution-to-understand-by-shahchaya-wd6u
Code\n\nclass Solution {\npublic:\n int numberOfRounds(string s, string f) {\n stringstream geek(s.substr(0,2));\n int x = 0;\n geek>>x;
shahchayan9
NORMAL
2024-06-22T09:32:56.660333+00:00
2024-06-22T09:32:56.660379+00:00
130
false
# Code\n```\nclass Solution {\npublic:\n int numberOfRounds(string s, string f) {\n stringstream geek(s.substr(0,2));\n int x = 0;\n geek>>x;\n stringstream geek1(f.substr(0,2));\n int y = 0;\n geek1>>y;\n stringstream geek2(s.substr(3,2));\n int x1 = 0;\n geek2>>x1;\n stringstream geek3(f.substr(3,2));\n int y1 = 0;\n geek3>>y1;\n int m=0;\n int t=0;\n if(x>y){\n m=(24-x-1+y)*4;\n }\n else if(x==y && y1>x1){\n m=0;\n t=1;\n }\n else if(x==y && x1>y1){\n m=23*4;\n }\n else{\n m=(y-x-1)*4;\n }\n if(t==1){\n if(x1>y1 && x!=y){\n int b=ceil((x1-y1)/15.0);\n // cout<<b;\n m+=96-b;\n return m;\n }\n // cout<<x1<<y1;\n y1-=y1%15;\n if(x1%15!=0)\n x1+=(15-x1%15);\n if(y1>x1)\n m+=(y1-x1)/15;\n return m;\n }\n m+=y1/15;\n x1=60-x1;\n m+=x1/15;\n return m;\n }\n};\n```
1
0
['C++']
0
the-number-of-full-rounds-you-have-played
100% fast | Simple short code with easy explanation
100-fast-simple-short-code-with-easy-exp-ze72
Intuition\n Describe your first thoughts on how to solve this problem. \nThink of playing chess rounds like taking steps. Every 15 minutes, a new round starts.
volcanicjava
NORMAL
2023-08-13T13:28:05.280396+00:00
2023-08-13T13:28:05.280432+00:00
184
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThink of playing chess rounds like taking steps. Every 15 minutes, a new round starts. The code takes your start and end times, and it figures out how many steps you took in terms of these 15-minute rounds:\n-> It checks when you started and stopped.\n-> If you played through midnight, it adds extra steps for the time after midnight.\n-> If you didn\'t start right at the beginning of a round, it moves you to the next round\'s starting point.\n-> Then, it simply counts the steps you took between your start and end.\n\n---\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- **Convert Time to Minutes:**\nThe minConvert function takes a time string (like "hh:mm") and converts it to the equivalent number of minutes in a day.\n\n- **Calculate Rounds Played:**\nIn the numberOfRounds function, we convert both login and logout times to minutes using minConvert.\n\n- **Adjust for Next Day:**\nIf the login time is later than the logout time, it means we\'ve played across midnight. So, we add 24 hours\' worth of minutes (1440) to the logout time.\n\n- **Round to Nearest 15 Minutes:**\nIf the login time is not at a 15-minute mark, we round it up to the next 15-minute interval.\n\n- **Calculate Rounds:**\nWe find the absolute difference between logout and login times and divide it by 15. This gives us the number of 15-minute rounds played.\n\n- **Return the Result:**\nThe calculated number of rounds played is the answer we return\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 minConvert(string &time){\n return stoi(time.substr(0,2))*60 + stoi(time.substr(3,2));\n }\n\n int numberOfRounds(string loginTime, string logoutTime) {\n int start = minConvert(loginTime), end = minConvert(logoutTime);\n\n if (start > end) end += 1440;\n if (start % 15) start=(start/15 + 1)*15;\n \n return abs(end - start)/15; \n }\n};\n```
1
0
['Math', 'C++']
0
the-number-of-full-rounds-you-have-played
Java straightforward bruteforce 33 lines
java-straightforward-bruteforce-33-lines-fm06
java\npublic class Solution {\n public int numberOfRounds(String loginTime, String logoutTime) {\n int start = convert(loginTime);\n int end =
ablaze6334
NORMAL
2023-07-19T16:33:00.752502+00:00
2023-07-19T16:33:00.752530+00:00
171
false
```java\npublic class Solution {\n public int numberOfRounds(String loginTime, String logoutTime) {\n int start = convert(loginTime);\n int end = convert(logoutTime);\n \n if (start > end) {\n return numberOfRounds(loginTime, "24:00") + numberOfRounds("00:00", logoutTime);\n }\n \n int round_start = 0;\n int round_end = 24 * 60;\n \n int count = 0;\n \n while (round_start <= round_end) {\n if (start <= round_start && round_start <= end && \n start <= round_start + 15 && round_start + 15 <= end) {\n count++;\n }\n \n round_start += 15;\n }\n \n return count;\n }\n \n private int convert(String time) {\n String[] parts = time.split(":");\n int hour = Integer.parseInt(parts[0]);\n int mins = Integer.parseInt(parts[1]);\n return hour * 60 + mins;\n }\n}\n```
1
0
['Java']
1
the-number-of-full-rounds-you-have-played
python3
python3-by-excellentprogrammer-cla4
\nclass Solution:\n def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:\n a=int(loginTime[0]+loginTime[1])*60+int(loginTime[3]+loginTime
ExcellentProgrammer
NORMAL
2022-08-22T09:55:10.595535+00:00
2022-08-22T09:55:10.595601+00:00
178
false
```\nclass Solution:\n def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:\n a=int(loginTime[0]+loginTime[1])*60+int(loginTime[3]+loginTime[4])\n b=int(logoutTime[0]+logoutTime[1])*60+int(logoutTime[3]+logoutTime[4])\n if (a>b):b+=24*60\n q, r = divmod(a, 15)\n a, b = q + int(r > 0), b // 15\n return max(0, b - a)\n```
1
0
[]
0
the-number-of-full-rounds-you-have-played
c++||easy solution ||comments
ceasy-solution-comments-by-gauravkumart-j1fd
```\n int n1=l1.length();\n int n2=l2.length();\n string s1=l1.substr(0,2);\n string s2=l2.substr(0,2);\n string t1=l1.substr(3,n1);
gauravkumart
NORMAL
2022-07-18T08:31:05.468070+00:00
2022-07-18T08:31:05.468104+00:00
112
false
```\n int n1=l1.length();\n int n2=l2.length();\n string s1=l1.substr(0,2);\n string s2=l2.substr(0,2);\n string t1=l1.substr(3,n1);\n string t2=l2.substr(3,n2);\n int res1=stoi(s1);\n int res2=stoi(s2);\n int tt1=stoi(t1);\n int tt2=stoi(t2);\n int ans=0;\n if(res1>res2){\n res2+=24;\n }\n if(res1==res2&&tt1>tt2){\n res2+=24;\n }\n //this is case is for when starting time is greater then ending time\n res1++;\n int temp1=res2-res1;\n temp1=temp1*60;\n temp1=temp1/15;\n ans+=temp1;\n //calculating the no of games possible in between hr \n int temp2=60-tt1;\n temp2=temp2/15;\n ans+=temp2;\n //temp2 is calculated by subracting from 60 because res1 is is increased by 1;\n //calculting the no of possible games in min\n int temp3=tt2/15;\n ans+=temp3;\n \n if(ans==-1){\n return 0;\n }\n \n \n \n return ans;
1
0
[]
0
the-number-of-full-rounds-you-have-played
[Python] straightforward, parse string
python-straightforward-parse-string-by-o-1mbh
\nclass Solution:\n def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:\n login = self.to_min(loginTime)\n logout = self.to_min(l
opeth
NORMAL
2022-06-25T16:40:08.495299+00:00
2022-06-25T16:40:08.495325+00:00
272
false
```\nclass Solution:\n def numberOfRounds(self, loginTime: str, logoutTime: str) -> int:\n login = self.to_min(loginTime)\n logout = self.to_min(logoutTime)\n \n if logout < login: # new day after midnight\n logout = logout + 24 * 60\n \n if logout - login < 15:\n return 0\n \n login = self.round_login(login)\n logout = self.round_logout(logout)\n \n return (logout - login) // 15\n \n \n def to_min(self, current_time: str) -> int:\n h, m = map(int, current_time.split(":"))\n return h * 60 + m\n \n def round_login(self, m: int):\n return m if m % 15 == 0 else m + (15 - m % 15)\n \n def round_logout(self, m: int):\n return m if m % 15 == 0 else m - (m % 15)\n```
1
0
['Python', 'Python3']
0