zlacker

[return to "My Favorite Programming Problem to Teach: Digit Length"]
1. tzs+ng[view] [source] 2019-11-11 01:32:57
>>jstrie+(OP)

  def digitLength(n):
      dlen = 1
      high = 9
      while n > high:
          dlen += 1
          high = 10*high + 9
      return dlen
◧◩
2. arctic+mh[view] [source] 2019-11-11 01:50:22
>>tzs+ng
No loops, and at least for a 64-bit type, you won't run out of stack space.

  fn digit_length_recursive(input: usize) -> usize {
      if input == 0 {
          0
      } else {
          1 + digit_length_recursive(input / 10)
      }
  }

  fn digit_length(input: usize) -> usize {
      std::cmp::max(digit_length_recursive(input), 1)
  }
[go to top]