740. Count Set Cost

Given two integers n and k, return the cost of flipping all set bits in n. One flip operation costs k.

Example 1:

Input: n = 9, k = 10

Output: 20

Explanation: Binary representation of 9 = 1001.

Number of set bits = 2, therefore cost = 2 * 10 = 20.

Example 2:

Input: n = 8, k = 5

Output: 5

Explanation: Binary representation of 8 = 1000.

Number of set bits = 1, therefore cost = 1 * 5 = 5.

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= n < 231
  • 0 <= k <= 104
0
class Solution {
public:
int setBitCost(int n, int k) {
 
}
};
Test Case

Input:

K
N