TheAlgorithms-Ruby/maths/number_of_digits.rb

23 lines
463 B
Ruby
Raw Normal View History

2021-01-26 23:15:39 +05:30
# Given a number, find number of digits in it.
def count_digits(n)
2021-02-06 23:05:54 -08:00
count = 0
temp = n
return 1 if n == 0
until temp.zero?
count += 1
temp /= 10
end
count
2021-01-26 23:15:39 +05:30
end
2021-02-06 23:05:54 -08:00
puts 'Number of digits in 8732 is ' + count_digits(8732).to_s
2021-01-26 23:15:39 +05:30
# Number of digits in 8732 is 4
2021-02-06 23:05:54 -08:00
puts 'Number of digits in 112233 is ' + count_digits(112_233).to_s
2021-01-26 23:15:39 +05:30
# Number of digits in 112233 is 6
2021-02-06 23:05:54 -08:00
puts 'Number of digits in 0 is ' + count_digits(0).to_s
2021-01-26 23:15:39 +05:30
# Number of digits in 0 is 1