0

something is wrong with my first loop where i find the value of the variable loops. when i comment out that particular loop and run the rest of the code, the code runs perfectly but when i run the code with that for loop, i am getting different answers. please help.

code:

public static void main(String [] args){
        Scanner sc = new Scanner (System.in);
        System.out.print("number : ");
        int n = sc.nextInt();
        int inc = 0;
        int loops = 0;
        
**// problem
        for(int i = 0; n>0; i++){

            int b = n>>=i;
            loops = i;
        }**
        
        
        

        for (int i = 0; i<=loops; i++){
            int bit = 1<<i;
            if((bit & n) == 0){

            }else{

                inc = inc + 1;
            }

        }


       if (inc==1){
           System.out.println("power");
       }else{
           System.out.println("not power");
       }

    }
Sri
  • 437
  • 1
  • 4
  • 13
ananya
  • 1
  • 4
    I suggest `num > 0 && (num&-num)==num` -- [bit twiddling hacks](https://graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2) – khelwood Jan 15 '22 at 18:24
  • 1
    That first for loop seems completely wrong. Not only does it not calculate the `loops` correctly, it also changes what you have stored in `n` – UnholySheep Jan 15 '22 at 18:27

1 Answers1

0

Here is one way to do it. But certainly not the most efficient.

int[] vals = {0, 1, 2, 4, 11, 13, 18, 28, 16, 46, 32 };

for (int v : vals) {
    System.out.printf("%2d - %s%n", v, isPowerOf2(v) ? "yes" : "no");
}

prints

 0 - no
 1 - yes
 2 - yes
 4 - yes
11 - no
13 - no
18 - no
28 - no
16 - yes
46 - no
32 - yes

The following simply counts the bits. If the count equals 1, then the value is a power of 2.

  • if v <= 0 return false.
  • initialize count
  • bump the count by 1 if lower order bit is set.
  • if greater than 1, immediately return false
  • else do an unsigned right shift by 1 and continue
  • when v == 0 terminate testing
  • return true since the count must be 1.
public static boolean isPowerOf2(int v) {
    if (v <= 0) {
        return false;
    }
    int count = 0;
    do {
        if ((count += (v & 1)) > 1) {
            return false;
        }
    } while ((v>>>=1) != 0);
    return true;
}

Without using bit manipulation one could simply use the Integer.bitCount() method to count the bits.

WJS
  • 36,363
  • 4
  • 24
  • 39