23 lines
583 B
Plaintext
23 lines
583 B
Plaintext
# n is assumed to be a non-negative integer
|
|
CREATE OR REPLACE FUNCTION binary_digits(n) as (
|
|
WITH RECURSIVE cte(num, str) as (
|
|
-- Base case
|
|
SELECT n, ''
|
|
UNION ALL
|
|
-- Recursive case: divide by 2 and build the binary string
|
|
SELECT num // 2, (num % 2) || str
|
|
FROM cte
|
|
WHERE num > 0
|
|
)
|
|
SELECT CASE WHEN str = '' THEN '0' ELSE str END
|
|
FROM cte
|
|
WHERE num = 0
|
|
LIMIT 1
|
|
);
|
|
|
|
select n, binary_digits(n)
|
|
from (select unnest(range(0, 6) || [50, 9000]) as n);
|
|
|
|
.maxwidth 200
|
|
select n, binary_digits(n) from (select 123456789123456789123456789123456789 as n)
|