I'm looking for code review, best practices and optimizations.
public final class DivThreeEfficiently {
private DivThreeEfficiently() {}
/**
* Returns true if the input number is divisible by three.
* Else returns false.
*
* @param n the input number
* @return true if input number is divisible by three
*/
public static boolean isMultipleOfThree(int n) {
if(n < 0) n = -n;
int evenCtr = 0;
int oddCtr = 0;
while (n != 0) {
if ((n & 1) == 1) {
oddCtr++;
}
n = n>>1;
if ((n & 1) == 1) {
evenCtr++;
}
n = n>>1;
}
return evenCtr == oddCtr;
}
}
public class DivThreeEfficientlyTest {
@Test
public void testEvenNegative() {
assertTrue(DivThreeEfficiently.isMultipleOfThree(-3));
assertTrue(DivThreeEfficiently.isMultipleOfThree(-6));
assertTrue(DivThreeEfficiently.isMultipleOfThree(-12));
}
@Test
public void testEvenPositive() {
assertTrue(DivThreeEfficiently.isMultipleOfThree(0));
assertTrue(DivThreeEfficiently.isMultipleOfThree(3));
assertTrue(DivThreeEfficiently.isMultipleOfThree(6));
}
@Test
public void testOddNegative() {
assertFalse(DivThreeEfficiently.isMultipleOfThree(-1));
assertFalse(DivThreeEfficiently.isMultipleOfThree(-4));
assertFalse(DivThreeEfficiently.isMultipleOfThree(-11));
}
@Test
public void testOddPositive() {
assertFalse(DivThreeEfficiently.isMultipleOfThree(1));
assertFalse(DivThreeEfficiently.isMultipleOfThree(4));
assertFalse(DivThreeEfficiently.isMultipleOfThree(11));
}
}
n % 3 == 0
is cheating? \$\endgroup\$isMultipleOfThree(21)
returnsfalse
. \$\endgroup\$