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. Doxin+Qr3[view] [source] 2024-06-06 08:38:14
>>lelant+3q3
It's assumed the input is an int. If not you can do len(str(int(x))) to make sure it is which strips leading zeroes off in the process.
[go to top]