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

后端 未结 6 879
猫巷女王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:01

    A very simple solution.

    int n = 8; // any integer and you can take it from user also
    for(;n>0;n++){
        if(n%2 != 0) {
            System.out.println("not a power of two")
            return;
        } // if ends here
        n = n/2;
    }// for ends here
    System.out.println("power of two")
    

提交回复
热议问题