RosettaCodeData/Task/Negative-base-numbers/11l/negative-base-numbers.11l
2023-07-01 13:44:08 -04:00

42 lines
1 KiB
Text
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

F encode_neg_base(=n, b)
I n == 0
R 0
[Int] out
L n != 0
(n, V rem) = divmod(n, b)
I rem < 0
n++
rem -= b
out.append(rem)
R reversed(out).map(String).join()
F decode_neg_base(nstr, b)
I nstr == 0
R 0
V total = 0
L(ch) reversed(nstr)
V i = L.index
total += Int(ch) * b ^ i
R total
print(Encode 10 as negabinary (expect 11110))
V result = encode_neg_base(10, -2)
print(result)
I decode_neg_base(result, -2) == 10
print(Converted back to decimal)
E
print(Error converting back to decimal)
print(Encode 146 as negaternary (expect 21102))
result = encode_neg_base(146, -3)
print(result)
I decode_neg_base(result, -3) == 146
print(Converted back to decimal)
E
print(Error converting back to decimal)
print(Encode 15 as negadecimal (expect 195))
result = encode_neg_base(15, -10)
print(result)
I decode_neg_base(result, -10) == 15
print(Converted back to decimal)
E
print(Error converting back to decimal)