Java’s Quirky Modulus

When it comes to them modulus operator, Java can be kinda quirky. Consider the statement:

a % b

If “a” is negative, the result will be negative. On would expect that -1%12 would return 11, as it does in Python. You can get this desired behavior in Java by doing:

(a % b + b) % b

I definitly wasted 5 minutes  debugging this, but at least now I know.

Reference: http://stackoverflow.com/questions/4412179/best-way-to-make-javas-modulus-behave-like-it-should-with-negative-numbers

Speak Your Mind

*

eleven − five =

Privacy Policy