How to check if a number is a power of 2

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

    This is another method to do it as well

    package javacore;
    
    import java.util.Scanner;
    
    public class Main_exercise5 {
        public static void main(String[] args) {
            // Local Declaration
            boolean ispoweroftwo = false;
            int n;
            Scanner input = new Scanner (System.in);
            System.out.println("Enter a number");
            n = input.nextInt();
            ispoweroftwo = checkNumber(n);
            System.out.println(ispoweroftwo);
        }
        
        public static boolean checkNumber(int n) {
            // Function declaration
            boolean ispoweroftwo= false;
            // if not divisible by 2, means isnotpoweroftwo
            if(n%2!=0){
                ispoweroftwo=false;
                return ispoweroftwo;
            }
            else {
                for(int power=1; power>0; power=power<<1) {
                    if (power==n) {
                        return true;
                    }
                    else if (power>n) {
                        return false;
                    }
                }
            }
            return ispoweroftwo;
        }
    }
    

提交回复
热议问题