Given an array of one's and zero's that represents a positive binary number convert the number to two's complement value.

Two's complement is the way most computers represent positive or negative integers. The most significant bit is negative. 

Examples:

-8 4 2 1 

[1,1,1,1] = -1

[1,0,0,0] = -8

[1,1,0,1] = -3

To get the two's complement negative notation of an integer, you take the number in binary. 

You then invert the digits, and add one to the result. 

For example:

[0,0,1,0] = 2 in base 10

[1,1,0,1] <- Flip the bits

   Add 1
   
[1,1,1,0] = -2

However, the arrays can have varying lengths, not just limited to 4.

Source: codewars | Difficulty: EASY
Tags: Bit manipulation

Data structures

Fundamentals

Starter code: def positive_to_negative(binary):
	

Solutions:
def positive_to_negative(binary):
	return [1 - d if 1 in binary[i:] else d for (i, d) in enumerate(binary, 1)]


def positive_to_negative(b):
	last = next((i for i in range(len(b) - 1, -1, -1) if b[i]), 0)
	return [1 - d for d in b[:last]] + b[last:]


def positive_to_negative(arr):
	flip = [0 if n == 1 else 1 for n in arr]
	for i in range(len(flip)):
		if flip[-(i + 1)] == 1:
			flip[-(i + 1)] = 0
		else:
			flip[-(i + 1)] = 1
			break
	return flip


def positive_to_negative(binary):
	binary = [not i for i in binary]
	for i in range(len(binary) - 1, -1, -1):
		if binary[i]:
			binary[i] = 0
		else:
			binary[i] = 1
			break
	return binary


def positive_to_negative(binary):
	flip = [int(not e) for e in binary]
	for i in range(len(flip) - 1, -1, -1):
		if flip[i] == 0:
			flip[i] = 1
			break
		flip[i] = 0
	return flip


def positive_to_negative(binary):
	b = []
	print('원래 이진수 :', binary)
	for bit in binary:
		if bit == 1:
			b.append(0)
		else:
			b.append(1)
	print('1과 0 바꾸기 :', b)
	c = 1
	for i in range(len(b)):
		if b[-1 - i] == 1 and c == 1:
			b[-1 - i] = 0
		elif b[-1 - i] == 0 and c == 1:
			c = 0
			b[-1 - i] = 1
		else:
			pass
	print('최종 :', b)
	return b


p = lambda b, c=1: [*p(b[:-1], 1 - b[-1] & c), 1 - b[-1] ^ c] if len(b) else []
positive_to_negative = p


def positive_to_negative(b):
	return [int(d) for d in f"{int(''.join((str(1 - d) for d in b)), 2) + 1:b}"] if 1 in b else b


def positive_to_negative(binary):
	n = len(binary)
	end = 0
	for i in range(n - 1, -1, -1):
		if binary[i] == 1:
			end = i
			break
	for i in range(end):
		binary[i] ^= 1
	return binary


def positive_to_negative(binary):
	if sum(binary) == 0:
		return binary
	steps = []
	index = 0
	zero_counter = 0
	for bin_num in binary:
		if binary[index] == 0:
			zero_counter += 1
			binary[index] = 1
		elif binary[index] == 1:
			binary[index] = 0
		steps.append(0)
		index += 1
	fill = list(steps)
	fill[-1] = 1
	index = len(binary) - 1
	while index >= 0:
		if index != len(binary) - 1:
			binary[index] += fill[index] + steps[index + 1]
		else:
			binary[index] += fill[index]
		if binary[index] == 2:
			binary[index] -= 2
			steps[index] += 1
		index -= 1
	return binary