MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / decimal_to_negative_base_2

Function decimal_to_negative_base_2

maths/base_neg2_conversion.py:1–31  ·  view source on GitHub ↗

This function returns the number negative base 2 of the decimal number of the input data. Args: int: The decimal number to convert. Returns: int: The negative base 2 number. Examples: >>> decimal_to_negative_base_2(0) 0 >>> decimal_

(num: int)

Source from the content-addressed store, hash-verified

1def decimal_to_negative_base_2(num: int) -> int:
2 """
3 This function returns the number negative base 2
4 of the decimal number of the input data.
5
6 Args:
7 int: The decimal number to convert.
8
9 Returns:
10 int: The negative base 2 number.
11
12 Examples:
13 >>> decimal_to_negative_base_2(0)
14 0
15 >>> decimal_to_negative_base_2(-19)
16 111101
17 >>> decimal_to_negative_base_2(4)
18 100
19 >>> decimal_to_negative_base_2(7)
20 11011
21 """
22 if num == 0:
23 return 0
24 ans = ""
25 while num != 0:
26 num, rem = divmod(num, -2)
27 if rem < 0:
28 rem += 2
29 num += 1
30 ans = str(rem) + ans
31 return int(ans)
32
33
34if __name__ == "__main__":

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected