Created
November 9, 2023 13:09
-
-
Save FrendaWinter/6c87b18ac86d1e10c0a21a42031d12ea to your computer and use it in GitHub Desktop.
Covert octal number to decimal number with Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# frozen_string_literal: true | |
# Usage: ruby octal_to_decimal.rb <octal_number> | |
# Covert octal number to decimal number | |
def octal_to_decimal n | |
exponent = 0 | |
result = 0 | |
n = n.to_s | |
(n.length - 1).downto(0) do |i| | |
result += n[i].to_i * pow(8, exponent) | |
exponent += 1 | |
end | |
result | |
end | |
# The pow() function returns the result of the first argument raised to the power of the second argument. | |
def pow(base, exponent) | |
if (exponent == 0) | |
return 1 | |
end | |
return base * pow(base, exponent - 1) | |
end | |
puts octal_to_decimal(ARGV[0]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment