4 ms·
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).
by gnuvince 7y ago
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
- a-nikolaev 7y agodef 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.
- gnuvince 7y agoThe problem statement said that the input would be natural numbers.
- lifthrasiir 7y agoWait, do natural numbers include zero? evil grin
- talaketu 7y agoNo support for that in Sloane's. https://oeis.org/A000027 https://oeis.org/A000027
- chopin 7y agoI looked up wikipedia which says there's no conclusive definition.
- lifthrasiir 7y agoThe joke is that, if you don't need to check if the input is negative because it is not a natural number, you can also choose a definition of the natural number without zero to avoid special casing it at all.