DEV Community

Discussion on: Daily Challenge #195 - No Zeroes for Heroes

Collapse
nijeesh4all profile image
Nijeesh Joshy • Edited on

Ruby

Regex

# using strings
def remove_trailing_zeros(number)
  number
    .to_s
    .gsub(/0{1,}$/,"")
    .to_i || 0
end

Recursion

def remove_trailing_zeros(number)
  return 0 if number == 0
  return remove_trailing_zeros(number / 10) if number % 10 == 0
  return number
end

TESTS

require "test/unit"


class RemoveTrailingZerosTest < Test::Unit::TestCase
  def test_remove_trailing_zeros
    assert_equal 907, remove_trailing_zeros(9070)
    assert_equal 21, remove_trailing_zeros(210000)
    assert_equal 1021, remove_trailing_zeros(10210)
    assert_equal 0, remove_trailing_zeros(0)
  end
end