0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

2のべき乗判定

0
Posted at

2^nは
2=10
4=100
8=1000
...
128=10000000
と常に最上位ビットが1、それ以下のビットがすべて0となり、これを-1するとすべてのビットが反転する
128-1=127=01111111
このためnとn-1の論理積は常に0、これが2のべき乗の判定式となる

public class main {
	public static void main(String [] args) {
		int data = 8;
		if((data & (data -1)) == 0) {
			System.out.print("true");
		}else {
			System.out.print("false");
		}
 	}
}
true
public class main {
	public static void main(String [] args) {
		int data = 9;
		if((data & (data -1)) == 0) {
			System.out.print("true");
		}else {
			System.out.print("false");
		}
 	}
}
false
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?