- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Program to find minimum possible sum by changing 0s to 1s k times from a list of numbers in Python?

Suppose we have a list of numbers called nums and another value k. We have to following operation k times: Select any number on the list. In the binary representation of that number, select a bit that is 0 and make it 1. Finally, we have to return the minimum possible sum of all the numbers after performing k operations. If the answer is too high, return result mode 10^9+7.

So, if the input is like nums = [4, 7, 3] k = 2, then the output will be 17, as the binary representation of 4 is 100, 3 is 011, and 7 is 111. Since we need to set 2 bits, we can set the bits of 4 to make it 111 (7). Then the total sum is then 7 + 7 + 3 = 17.

To solve this, we will follow these steps:

ans := 0, i := 0

while k is non-zero, do

for each n in nums, do

if (n / 2^i) is even, then

ans := ans + 2^i

k := k - 1

if k is same as 0, then

come out from the loop

i := i + 1

return (ans + sum of all elements of nums) mod m

Let us see the following implementation to get better understanding:

## Example

class Solution: def solve(self, nums, k): m = (10 ** 9 + 7) ans = 0 i = 0 while k: for n in nums: if (n >> i) & 1 == 0: ans += 1 << i k -= 1 if k == 0: break i += 1 return (ans + sum(nums)) % m ob = Solution() nums = [4, 7, 3] k = 2 print(ob.solve(nums, k))

## Input

[4, 7, 3], 2

## Output

17

- Related Questions & Answers
- Program to find maximum sum by removing K numbers from ends in python
- Program to find sum of minimum trees from the list of leaves in python
- C Program to construct DFA accepting odd numbers of 0s and 1s
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Program to find minimum possible maximum value after k operations in python
- Program to find length of longest set of 1s by flipping k bits in Python
- Python - List Initialization with alternate 0s and 1s
- Program to find elements from list which have occurred at least k times in Python
- Find minimum k records from tuple list in Python
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Program to find minimum largest sum of k sublists in C++
- How to find sum a list of numbers in Python?
- Program to find ith element by rotating k times to right
- Program to find missing numbers from two list of numbers in Python
- Program to check sum of two numbers is up to k from sorted List or not in Python