How to check if a number is a power of 2

后端 未结 25 1455
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 03:30

Today I needed a simple algorithm for checking if a number is a power of 2.

The algorithm needs to be:

  1. Simple
  2. Correct for any ulong
相关标签:
25条回答
  • 2020-11-22 04:04

    This program in java returns "true" if number is a power of 2 and returns "false" if its not a power of 2

    // To check if the given number is power of 2
    
    import java.util.Scanner;
    
    public class PowerOfTwo {
        int n;
        void solve() {
            while(true) {
    //          To eleminate the odd numbers
                if((n%2)!= 0){
                    System.out.println("false");
                    break;
                }
    //  Tracing the number back till 2
                n = n/2;
    //  2/2 gives one so condition should be 1
                if(n == 1) {
                    System.out.println("true");
                    break;
                }
            }
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Scanner in = new Scanner(System.in);
            PowerOfTwo obj = new PowerOfTwo();
            obj.n = in.nextInt();
            obj.solve();
        }
    
    }
    
    OUTPUT : 
    34
    false
    
    16
    true
    
    0 讨论(0)
  • 2020-11-22 04:05

    Here's a simple C++ solution:

    bool IsPowerOfTwo( unsigned int i )
    {
        return std::bitset<32>(i).count() == 1;
    }
    
    0 讨论(0)
  • 2020-11-22 04:05
    int isPowerOfTwo(unsigned int x)
    {
        return ((x != 0) && ((x & (~x + 1)) == x));
    }
    

    This is really fast. It takes about 6 minutes and 43 seconds to check all 2^32 integers.

    0 讨论(0)
  • 2020-11-22 04:07

    Here is another method I devised, in this case using | instead of & :

    bool is_power_of_2(ulong x) {
        if(x ==  (1 << (sizeof(ulong)*8 -1) ) return true;
        return (x > 0) && (x<<1 == (x|(x-1)) +1));
    }
    
    0 讨论(0)
  • 2020-11-22 04:10
    bool isPow2 = ((x & ~(x-1))==x)? !!x : 0;
    
    0 讨论(0)
  • 2020-11-22 04:15
    bool isPowerOfTwo(int x_)
    {
      register int bitpos, bitpos2;
      asm ("bsrl %1,%0": "+r" (bitpos):"rm" (x_));
      asm ("bsfl %1,%0": "+r" (bitpos2):"rm" (x_));
      return bitpos > 0 && bitpos == bitpos2;
    }
    
    0 讨论(0)
提交回复
热议问题