LeetCode 3871 Elixir solution

When using Java, C++, Python, or TypeScript, we can solve this problem with a for loop.

In Elixir, we use tail recursion instead because the Elixir/Erlang VM can optimize tail-recursive calls, allowing them to execute without accumulating stack frames.


Time complexity: O(log n)
Space complexity: O(1)


Elixir

defmodule Solution do
  @spec count_commas(n :: integer) :: integer
  def count_commas(n) do
    count(n, 1000, 0)
  end

  defp count(n, start, result) when start <= n do
    count(n, start * 1000, result + n - start + 1)
  end

  defp count(_n, _start, result) do
    result
  end
end