Skip to content

Commit 4cabb19

Browse files
committed
added bit manipulation snippets
1 parent 630477c commit 4cabb19

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
title: Bit Counting
3+
description: Counts the bits in an integer
4+
author: Mcbencrafter
5+
tags: math,number,bits,bit-counting
6+
---
7+
8+
```java
9+
public static int countBits(int number) {
10+
int bits = 0;
11+
12+
while (number > 0) {
13+
bits += number & 1;
14+
number >>= 1;
15+
}
16+
17+
return bits;
18+
}
19+
20+
// Usage:
21+
int number = 5;
22+
System.out.println(countBits(5)); // 2 (101)
23+
```
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
---
2+
title: Is Power Of Two
3+
description: Checks if a number is a power of two
4+
author: Mcbencrafter
5+
tags: math,number,bit,power-of-two
6+
---
7+
8+
```java
9+
public static boolean isPowerOfTwo(int number) {
10+
return (number > 0) && ((number & (number - 1)) == 0);
11+
}
12+
13+
// Usage:
14+
int number = 16;
15+
System.out.println(isPowerOfTwo(5)); // true (2^4)
16+
```

0 commit comments

Comments
 (0)