Skip to main content
deleted 55 characters in body; edited title
Source Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238

Check Efficiently checking if a number is divisible by 3, efficiently

Efficient way to check if a number is multiple of three. LookingI'm looking for code review, best practices and optimizations.

Check if a number is divisible by 3, efficiently

Efficient way to check if a number is multiple of three. Looking for code review, best practices and optimizations.

Efficiently checking if a number is divisible by 3

I'm looking for code review, best practices and optimizations.

Notice removed Reward existing answer by 200_success
Bounty Ended with maaartinus's answer chosen by 200_success
Notice added Reward existing answer by 200_success
Bounty Started worth 150 reputation by 200_success
Tweeted twitter.com/#!/StackCodeReview/status/475168182953467904
Question Protected by rolfl
Source Link
JavaDeveloper
  • 8.5k
  • 29
  • 93
  • 162

Check if a number is divisible by 3, efficiently

Efficient way to check if a number is multiple of three. 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));
    }
}