2
$\begingroup$

I want to check if a number has an even or odd number of digits.

10 would be even because it has 2 digits

300 would be odd because it has 3 digits

986786 would be even, because it has 6 digits

Seems like I would be dividing it by a power of 10, is that right?

$\endgroup$
0

2 Answers 2

10
$\begingroup$

IntegerLength:

OddQ@IntegerLength[{10, 300, 986786}]
(* {False, True, False} *)
$\endgroup$
3
$\begingroup$
EvenQ@Floor@Log[10, N@{10, 300, 986786}]
(* {False, True, False} *)
$\endgroup$
2
  • $\begingroup$ good approach to know in case you need to port your code. The N@ isn't needed by the way (maybe it affects performance though ) $\endgroup$
    – george2079
    Dec 3, 2013 at 20:46
  • 3
    $\begingroup$ Indeed, it is two orders of magnitude faster to give Log the float value than to let Floor process the integer result. IntegerLength is another order of magnitude faster than that.. $\endgroup$
    – george2079
    Dec 3, 2013 at 20:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.