LeetCode-in-Java

3954. Sum of Compatible Numbers in Range I

Easy

You are given two integers n and k.

A positive integer x is called compatible if it satisfies both of the following conditions:

Return the sum of all compatible integers x.

Note:

Example 1:

Input: n = 2, k = 3

Output: 10

Explanation:

The compatible integers are:

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:

Solution

public class Solution {
    public int sumOfGoodIntegers(int n, int k) {
        int sum = 0;
        int l = k + n;
        int s = n - k;
        if (s < 0) {
            s = 1;
        }
        for (int i = s; i <= l; i++) {
            if ((i & n) == 0) {
                sum += i;
            }
        }
        return sum;
    }
}