Added 2's complement

This commit is contained in:
devansh-07
2020-10-19 11:02:25 +05:30
parent 3ba50015ef
commit a60525edbc
3 changed files with 28 additions and 0 deletions

View File

@@ -71,3 +71,4 @@ from .multiplyComplexNumbersFunc import *
from .geomProgrFunc import *
from .geometricMeanFunc import *
from .harmonicMeanFunc import *
from .binary2sComplement import *

View File

@@ -0,0 +1,26 @@
from .__init__ import *
def binary2sComplementFunc(maxDigits=10):
digits = random.randint(1, maxDigits)
question = ''.join([str(random.randint(0, 1)) for i in range(digits)]).lstrip('0')
answer = []
for i in question:
answer.append(str(int(not bool(int(i)))))
carry = True
j = len(answer) - 1
while j >= 0:
if answer[j] == '0':
answer[j] = '1'
carry = False
break
answer[j] = '0'
j -= 1
if j == 0 and carry == True:
answer.insert(0, '1')
problem = "2's complement of " + question + " ="
solution = ''.join(answer).lstrip('0')
return problem, solution