Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s
36-character digit alphabet '0..9A..Z' supports any base 2..36. Loop
divides the magnitude by base and prepends the digit:
while !m > 0 do
acc := String.make 1 digits.[!m mod base] ^ !acc;
m := !m / base
done
Special-cases n = 0 -> '0' and prepends '-' for negatives.
Test cases (length, since the strings differ in alphabet):
255 hex 'FF' 2
1024 binary '10000000000' 11
100 dec '100' 3
0 any base '0' 1
sum 17
Combines digits.[i] (string indexing) + String.make 1 ch + String
concatenation in a loop.
61 baseline programs total.
20 lines
457 B
OCaml
20 lines
457 B
OCaml
let to_base_n n base =
|
|
let digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" in
|
|
if n = 0 then "0"
|
|
else begin
|
|
let m = ref (abs n) in
|
|
let acc = ref "" in
|
|
while !m > 0 do
|
|
acc := String.make 1 digits.[!m mod base] ^ !acc;
|
|
m := !m / base
|
|
done;
|
|
if n < 0 then "-" ^ !acc else !acc
|
|
end
|
|
|
|
;;
|
|
|
|
String.length (to_base_n 255 16) +
|
|
String.length (to_base_n 1024 2) +
|
|
String.length (to_base_n 100 10) +
|
|
String.length (to_base_n 0 16)
|