Count Length of a Number

excerpt: This covers the basics of counter and reducing input value by integer division. tags: while-loop reducing-value-by-integer-division counter

Write a method to count the length of a given number. The implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
def count(input)
  counter = 0
  
  n = input
  
  while n != 0
    n /= 10
    counter += 1
  end
  
  counter
end

p count(1)

The integer division can be used to chop off the rightmost digit from the given input.

Building Blocks

  • while Loop
  • Reduction of Input Value
  • Reducing Value by Integer Division
  • Counter