알고리즘/코드워

[python] Two's Complement

(ㅇㅅㅎ) 2023. 7. 18. 09:49
728x90
반응형

 

https://www.codewars.com/kata/58d4785a2285e7795c00013b/train/python

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

 

def to_twos_complement(binary, bits):
    return int(binary.replace(' ', ''), 2) -2 ** bits * int(binary[0])

def from_twos_complement(n, bits):
    return bin(n & (2**bits-1))[2:].zfill(bits)
반응형

'알고리즘 > 코드워' 카테고리의 다른 글

[python] Binomial Expansion  (0) 2023.01.16
[python]Can you sum?  (0) 2022.12.06
[python]Squash the bugs  (0) 2021.03.08
[python]Holiday VI - Shark Pontoon  (0) 2020.12.03
[python]Exclusive "or" (xor) Logical Operator  (0) 2020.12.02