Comments on When The Ternary Is Balance
Parent
When The Ternary Is Balance
Inspired by this Rosetta Code article.
Introduction
Balanced Ternary is a method of representing integers using -1, 0 and 1 in base 3.
Decimal 11 = (1 * 32) + (1 * 31) + (−1 * 30) = [1,1,-1] or "++-"
Decimal 6 = (1 * 32) + (−1 * 31) + (0 * 30) = [1,-1,0] or "+-0"
Task
Given any integer, you must give its balanced ternary representation in any permitted format (array, string, etc.)
Your program must support all integers present within its maximum integer limit.
Test Cases
Reference implementation with first 200 values
5 +--
6 +-0
11 ++-
65 +-++-
-44 -++0+
-540 -+-+000
Scoring
This is code-golf. Shortest answer in each language wins.
[Haskell], 78 77 bytes …
3y ago
[JavaScript (Node.js)], 47 40 …
3y ago
[Python 3], 78 bytes …
3y ago
Post
JavaScript (Node.js), 47 40 50 49 bytes
-1 (possibly -3) bytes thanks to Shaggy!
f=(n,s='0')=>n?f(n/3+n%3/2|0,'')+"+-0+-"[n%3+2]:s
A basic recursive solution.
2 comment threads