Sum of Compatible Numbers in Range I Problem
#3954
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3954.
You are given two integers n and k.
A positive integer x is called compatible if it satisfies both of the following conditions:
abs(n - x) <= k(n & x) == 0
Return the sum of all compatible integers x.
Note:
- Here,
&denotes the bitwise AND operator. - The absolute difference between integers
iandjis defined asabs(i - j).
Example 1:
Input: n = 2, k = 3
Output: 10
Explanation:
The compatible integers are:
- x = 1, since abs(2 - 1) = 1 and 2 & 1 = 0.
- x = 4, since abs(2 - 4) = 2 and 2 & 4 = 0.
- x = 5, since abs(2 - 5) = 3 and 2 & 5 = 0.
Thus, the answer is 1 + 4 + 5 = 10.
Example 2:
Input: n = 5, k = 1
Output: 0
Explanation:
There are no compatible integers in the range [4, 6]. Thus, the answer is 0.
Constraints:
1 <= n <= 1001 <= k <= 100
Solution
Approach: Simulation
Only x in [max(1, n - k), n + k] can satisfy abs(n - x) <= k, and k is small. Loop over that range and add x to the answer whenever n & x == 0.
Complexity: time O(k), space O(1).
class Solution:
def sumOfGoodIntegers(self, n: int, k: int) -> int:
ans = 0
for x in range(max(1, n - k), n + k + 1):
if (n & x) == 0:
ans += x
return ans