let pal_dec n =
  let s = string_of_int n in
  let len = String.length s in
  let p = ref true in
  for i = 0 to len / 2 - 1 do
    if s.[i] <> s.[len - 1 - i] then p := false
  done;
  !p

let to_binary n =
  if n = 0 then "0"
  else
    let buf = Buffer.create 32 in
    let m = ref n in
    let stack = ref [] in
    while !m > 0 do
      stack := (!m mod 2) :: !stack;
      m := !m / 2
    done;
    List.iter (fun d -> Buffer.add_string buf (string_of_int d)) !stack;
    Buffer.contents buf

let pal_bin n =
  let s = to_binary n in
  let len = String.length s in
  let p = ref true in
  for i = 0 to len / 2 - 1 do
    if s.[i] <> s.[len - 1 - i] then p := false
  done;
  !p

let euler36 limit =
  let sum = ref 0 in
  for n = 1 to limit - 1 do
    if pal_dec n && pal_bin n then sum := !sum + n
  done;
  !sum

;;

euler36 1000
