[LeetCode] Sum of Compatible Numbers in Range I

3954. Sum of Compatible Numbers in Range I

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 i and j is defined as abs(i - j).
1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int sumOfGoodIntegers(int n, int k) {
int res = 0;
for(int i = max(0,n - k); i <= n + k; i++) {
if(!(n&i)) res += i;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/sum-of-compatible-numbers-in-range-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.