zlacker

[return to "My Favorite Programming Problem to Teach: Digit Length"]
1. gnuvin+Wc[view] [source] 2019-11-11 00:34:34
>>jstrie+(OP)
By using a do-while loop, you don't have to handle the special case of zero (although one could argue that the do-while loop is the special handling for zero). Python does not have such a loop, so you need to do an infinite loop with an explicit break and I know some people recoil in horror at the sight of such code.

    def digitlength(n):
        digits = 0
        while True:
            digits += 1
            n /= 10
            if n == 0:
                return digits
◧◩
2. a-niko+Ke[view] [source] 2019-11-11 01:04:47
>>gnuvin+Wc

    def digitlength(n):
        digits = 1
        while (n > 9):
            digits += 1
            n /= 10
        return digits
Also may want to set n = abs(n) in the beginning, in case n is negative.
◧◩◪
3. gnuvin+Pe[view] [source] 2019-11-11 01:06:25
>>a-niko+Ke
The problem statement said that the input would be natural numbers.
[go to top]