How to get the Nth digit of a number from the right in Ruby

1 Answer

0 votes
# Returns the N-th digit of a number counting from the right.
#
# Examples:
#   get_nth_digit_from_right(12345, 1) # => 5
#   get_nth_digit_from_right(12345, 2) # => 4
#   get_nth_digit_from_right(12345, 3) # => 3
#
# @param input_number [Integer]
#   The number to inspect.
#
# @param digit_position [Integer]
#   The digit position (1-based, from the right).
#
# @return [Integer]
#   The digit at the specified position.
#
# @raise [ArgumentError]
#   If digit_position is less than 1.
def get_nth_digit_from_right(input_number, digit_position)
  raise ArgumentError, "Digit position must be greater than 0." if digit_position < 1

  # Handle negative numbers.
  absolute_number = input_number.abs

  # Calculate 10^(digit_position - 1) using integer arithmetic.
  divisor = 1

  (digit_position - 1).times do
    divisor *= 10
  end

  # Shift the desired digit to the ones place.
  shifted_number = absolute_number / divisor

  # Extract the digit.
  shifted_number % 10
end

# Program entry point.
def main
  input_number = 12_745

  first_digit = get_nth_digit_from_right(input_number, 1)
  third_digit = get_nth_digit_from_right(input_number, 3)
  fifth_digit = get_nth_digit_from_right(input_number, 5)

  puts "Number: #{input_number}"
  puts "1st digit from right: #{first_digit}"
  puts "3rd digit from right: #{third_digit}"
  puts "5th digit from right: #{fifth_digit}"
end

main


# run:
#
# Number: 12745
# 1st digit from right: 5
# 3rd digit from right: 7
# 5th digit from right: 1
#

 



answered 18 hours ago by avibootz
...