- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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 Articles
- 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
- Program to find minimum possible maximum value after k operations 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
- Python - List Initialization with alternate 0s and 1s
- Program to find length of longest set of 1s by flipping k bits in Python
- Program to check sum of two numbers is up to k from sorted List or not in Python
- Program to find number of pairs from N natural numbers whose sum values are divisible by k in Python
- Find minimum k records from tuple list in Python
- Program to find elements from list which have occurred at least k times in Python
- Program to find minimum largest sum of k sublists in C++
- Program to find three unique elements from list whose sum is closest to k Python
- Check if it is possible to rearrange a binary string with alternate 0s and 1s in Python
- Python program to find the group sum till each K in a list