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

后端 未结 6 877
猫巷女王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 19:50

    double input = 22;
    
    while(((input != 2) && input % 2 == 0) || input == 1) {
     input = input /2;
    }
    
    return input == 2;
    

    Keep dividing it by 2 until you reach 1 or an odd number. If it reaches 1 it's a power of 2, otherwise it isn't.

提交回复
热议问题