zlacker

[return to "My favorite programming problem to teach: Digit length (2019)"]
1. jcynix+Bo3[view] [source] 2024-06-06 08:01:57
>>equili+(OP)
Hmm, my solution would be to convert the number to a string and return its length. Easily done in Perl:

  perl -e 'print length 987654'
  6
Similarly easy in Lisp with either of write-to-string, prin1-to-string, and princ-to-string. I expect python to have some such built-in function too.
◧◩
2. quirin+up3[view] [source] 2024-06-06 08:14:17
>>jcynix+Bo3
It is mentioned at the end of the article. In Python it's as simple as len(str(x)).
◧◩◪
3. lelant+3q3[view] [source] 2024-06-06 08:19:51
>>quirin+up3
> In Python it's as simple as len(str(x)).

I consider that to be wrong - leading zeros are not part of the number and should be ignored. Using `len(str(x))` results in `2` for the input `"01"`.

◧◩◪◨
4. Thorre+0s3[view] [source] 2024-06-06 08:39:52
>>lelant+3q3
The input "01" fails all the other solutions as well. You can't divide or take the log of a string.
◧◩◪◨⬒
5. lelant+Ps3[view] [source] 2024-06-06 08:48:05
>>Thorre+0s3
> The input "01" fails all the other solutions as well. You can't divide or take the log of a string.

The other solutions fail differently - they generates an error and stop processing.

The `len(str())` failure doesn't generate an error, and doesn't stop processing, it simply returns the wrong answer.

So, the `len` approach is wrong, the other approaches are right.

[go to top]