How to check if a number is a power of 2

后端 未结 25 1904
爱一瞬间的悲伤
爱一瞬间的悲伤 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
    

提交回复
热议问题