How to write 4 different functions that check if a number is a power of 2 in C#

1 Answer

0 votes
public class PowerOfTwoCheck {

    // Method A: Bit-counting 
    public static boolean isPowerOfTwoA(int x) {
        if (x <= 0) return false;
        return Integer.bitCount(x) == 1;
    }

    // Method B: Bitwise trick (classic)
    // A power of two has exactly one bit set, so x & (x - 1) == 0
    public static boolean isPowerOfTwoB(int x) {
        return x > 0 && (x & (x - 1)) == 0;
    }

    // Method C: Repeated division
    public static boolean isPowerOfTwoC(int x) {
        if (x <= 0) return false;
        while (x % 2 == 0) {
            x /= 2;
        }
        return x == 1;
    }

    // Method D: Using Math.log2
    public static boolean isPowerOfTwoD(int x) {
        if (x <= 0) return false;
        double log = Math.log(x) / Math.log(2);
        return Math.abs(log - Math.round(log)) < 1e-10;
    }

    public static void main(String[] args) {
        int test1 = 16;   // true
        int test2 = 18;   // false

        System.out.println("A: " + isPowerOfTwoA(test1) + ", " + isPowerOfTwoA(test2));
        System.out.println("B: " + isPowerOfTwoB(test1) + ", " + isPowerOfTwoB(test2));
        System.out.println("C: " + isPowerOfTwoC(test1) + ", " + isPowerOfTwoC(test2));
        System.out.println("D: " + isPowerOfTwoD(test1) + ", " + isPowerOfTwoD(test2));
    }
}



/*
OUTPUT:

A: true, false
B: true, false
C: true, false
D: true, false

*/

 



answered Apr 2 by avibootz

Related questions

...