Determine whether a number is 2 to the k power

Determine whether a number is 2 to the power of k (the value of k is not considered here).
Regarding this question, we must first start with the essence of the question: What are the characteristics of the number of the k power of 2?
First, familiarize yourself with a few common ones (the corresponding binary sequence is in parentheses):

2(10) 4(100) 8(1000) 16(10000)

We found that these numbers to the power of 2 have only one 1 in the binary sequence.
Then start here. Introduce the following two methods:

  1. method one

Idea: Shift the binary sequence of the number by i places to the right until the first 1 is encountered, and then determine whether the number is 1, if it is 1, it means that the binary sequence of the number has only one 1, which is the number of times of 2. .
Code:

package shujiazuoye;

import java.util.Scanner;

/*
* 如何判断一个数是不是2的几次方
* */
public class AboutTwo {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc=new Scanner(System.in);

        System.out.println("请输入你要判断的数字:");
        int num=sc.nextInt();
        aboutTwo(num);
    }
    private static void aboutTwo(int num) {
    
    

        while((num&1)!=1){
    
    
            num=num>>1;
        }
            if(num==1){
    
    
                System.out.println("是2的k次方");
            }else{
    
    
                System.out.println("不是2的k次方");
            }

    }
}

2. Method 2

Idea:
Assuming this number is n, if n&(n-1) is 0, then n is 2 to the k power; assuming n&(n-1) is 1, then n is not 2 to the k power.
Code:

package shujiazuoye;
import java.util.Scanner;

public class AboutTwo1 {
    
    
    public static void main(String[] args) {
    
    
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入要判断的数字:");
        int num=sc.nextInt();
        aboutTwo(num);

    }
    private static void aboutTwo(int num) {
    
    
        if(((num)&(num-1))==0){
    
    
            System.out.println("是2的k次方");
        }else{
    
    
            System.out.println("不是2的k次方");
        }
    }

}

Guess you like

Origin blog.csdn.net/weixin_43815275/article/details/112442660