Bit manipulation
[Leetcode 136] Single Number
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
1 | Input: nums = [2,2,1] |
Example 2:
1 | Input: nums = [4,1,2,1,2] |
Example 3:
1 | Input: nums = [1] |
Constraints:
- 1 <= nums.length <= 3 * 104
- -3 * 104 <= nums[i] <= 3 * 104
- Each element in the array appears twice except for one element which appears only once.
Solution:
1 | class Solution: |
[Leetcode 190] Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
Note:
- Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned.
- In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.
Example 1:
1 | Input: n = 00000010100101000001111010011100 |
Example 2:
1 | Input: n = 11111111111111111111111111111101 |
Constraints:
- The input must be a binary string of length 32
Solution:
1 | class Solution: |
[Leetcode 338] Counting Bits
Given an integer n, return an array ans of length n + 1 such that for each i (0 <= i <= n), ans[i] is the number of 1’s in the binary representation of i.
Example 1:
1 | Input: n = 2 |
Example 2:
1 | Input: n = 5 |
Constraints:
- 0 <= n <= 105
Follow up:
- It is very easy to come up with a solution with a runtime of O(n log n). Can you do it in linear time O(n) and possibly in a single pass?
Can you do it without using any built-in function (i.e., like __builtin_popcount in C++)?
Solution:
1 | class Solution: |
[Leetcode 1318] Minimum Flips to Make a OR b Equal to c
Given 3 positives numbers a, b and c. Return the minimum flips required in some bits of a and b to make ( a OR b == c ). (bitwise OR operation).
Flip operation consists of change any single bit 1 to 0 or change the bit 0 to 1 in their binary representation.
Example 1:
1 | Input: a = 2, b = 6, c = 5 |
Example 2:
1 | Input: a = 4, b = 2, c = 7 |
Example 3:
1 | Input: a = 1, b = 2, c = 3 |
Constraints:
- 1 <= a <= 10^9
- 1 <= b <= 10^9
- 1 <= c <= 10^9
Solution:
1 | class Solution: |