HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Check if a given integer is power of two

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
powertwocheckgiveninteger

Problem

Given an integer, check if it's the power of two.

class Main {
  static class Solution {
    private final boolean answer;

    Solution(int num) {
      if (num <= 0) {
        answer = false;
      }
      else if ((num & (num - 1)) == 0) {
        answer = true;
      }
      else {
        answer = false;
      }
    }

    public boolean isPowerOfTwo() {
      return answer;
    }
  }

  public static void runTests() {
    // Falsy
    System.out.println(new Solution(-1).isPowerOfTwo());
    System.out.println(new Solution(0).isPowerOfTwo());
    System.out.println(new Solution(Integer.MAX_VALUE).isPowerOfTwo());
    System.out.println(new Solution(Integer.MIN_VALUE).isPowerOfTwo());

    //Truthy
    System.out.println(new Solution(1).isPowerOfTwo());
    System.out.println(new Solution(128).isPowerOfTwo());
    System.out.println(new Solution(1024).isPowerOfTwo());
  }

  public static void main(String[] args) {
    runTests();
  }
}

Solution

Code organization

There is nothing in the description and the posted code to justify storing the result of the "is power of 2" calculation in a class.
It would be better to simply return it.
The code is also simple enough that you could collapse the if-else chain to a single line:

public static boolean isPowerOfTwo(int num) {
    return num > 0 && (num & (num - 1)) == 0;
}


Testing

I suggest to look into proper unit testing methods,
for example JUnit4 which comes bundled in most IDEs.
The tests you wrote in main would look like this using JUnit4:

private boolean isPowerOfTwo(int num) {
    return Solution.isPowerOfTwo(num);
}

@Test
public void minus1_should_not_be_power_of_2() {
    assertFalse(isPowerOfTwo(-1));
}

@Test
public void zero_should_not_be_power_of_2() {
    assertFalse(isPowerOfTwo(0));
}

// ... and so on

Code Snippets

public static boolean isPowerOfTwo(int num) {
    return num > 0 && (num & (num - 1)) == 0;
}
private boolean isPowerOfTwo(int num) {
    return Solution.isPowerOfTwo(num);
}

@Test
public void minus1_should_not_be_power_of_2() {
    assertFalse(isPowerOfTwo(-1));
}

@Test
public void zero_should_not_be_power_of_2() {
    assertFalse(isPowerOfTwo(0));
}

// ... and so on

Context

StackExchange Code Review Q#150780, answer score: 11

Revisions (0)

No revisions yet.