Find if a number is a power of two without math function or log function

后端 未结 6 874
猫巷女王i
猫巷女王i 2020-11-30 19:27

I want to find if a user entered number is a power of two or not.

My code doesn\'t work.

public class power_of_two
{  
    public static void main         


        
6条回答
  •  自闭症患者
    2020-11-30 20:10

    You can use the bitwise AND (&) operator:

    return (num & -num) == num
    

    Why this works?

    Consider the number 8, what it is in binary (assuming 32-bits)?

    0000 0000 0000 0000 0000 0000 0000 1000
    

    Now let's see how -8 is represented? 1

    1111 1111 1111 1111 1111 1111 1111 1000
    

    Finally.. let's calculate 8 & -8:

    0000 0000 0000 0000 0000 0000 0000 1000   8
    ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓   &
    1111 1111 1111 1111 1111 1111 1111 1000  -8
    ---------------------------------------
    0000 0000 0000 0000 0000 0000 0000 1000   8    ¯\_(ツ)_/¯
    

    Now let's take another example, let's say 7, which is not power of two.

    0000 0000 0000 0000 0000 0000 0000 0111   7
    ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓ ↓↓↓↓   &                       
    1111 1111 1111 1111 1111 1111 1111 1001  -7
    ---------------------------------------
    0000 0000 0000 0000 0000 0000 0000 0001  != 7  ¯\_(ة_ة)_/¯
    

    As mentioned by @arshajii, think what will happen if num is zero.. I'll leave the solution for you :)

    1 A good way to remember how to calculate that: Begin from the rightmost bit, for each 0 you see, don't change it, when you see 1, leave it and proceed, but from now on, invert all bits. I tried to explain this more here.

提交回复
热议问题