Android: which operator for modulo (% doesn't work with negative numbers)
45,881
Solution 1
%
does a remainder operation in Java.
To get a proper modulus, you can use the remainder in a function:
It's shortest using ternary operator to do the sign fixup:
private int mod(int x, int y)
{
int result = x % y;
return result < 0? result + y : result;
}
For those who don't like the ternary operator, this is equivalent:
private int mod(int x, int y)
{
int result = x % y;
if (result < 0)
result += y;
return result;
}
Solution 2
Because if you divides -2 by 6, you will get -2 as remainder. % operator will give the remainder just like below;
int remainder = 7 % 3; // will give 1
int remainder2 = 6 % 2; // will give 0
To get the modulo:
// gives m ( mod n )
public int modulo( int m, int n ){
int mod = m % n ;
return ( mod < 0 ) ? mod + n : mod;
}
Author by
c0dehunter
Updated on July 09, 2022Comments
-
c0dehunter over 1 year
-
c0dehunter almost 12 yearsOK, but then how do I get mod in Android?
-
Mahdi almost 10 years@don roby: what this operator means: return result < 0? result + y : result; thanks
-
Don Roby almost 10 years@Kenji - see wikipedia on ternary operator ?: