Skip to content

Commit 2a41500

Browse files
committed
find absolute value of int without branching / with branching but using BIT operations
1 parent 0c81975 commit 2a41500

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@
5757
- [x] [Bit Hacks — Part 2 (Playing with k’th bit)](http://www.techiedelight.com/bit-hacks-part-2-playing-kth-bit/)
5858
- [x] [Bit Hacks — Part 3 (Playing with rightmost set bit of a number)](http://www.techiedelight.com/bit-hacks-part-3-playing-rightmost-set-bit-number/)
5959
- [x] [Bit Hacks — Part 4 (Playing with letters of English alphabet)](http://www.techiedelight.com/bit-hacks-part-4-playing-letters-english-alphabet/)
60-
- [ ] [Bit Hacks — Part 5 (Find absolute value of an integer without branching)](http://www.techiedelight.com/bit-hacks-part-5-find-absolute-value-integer-without-branching/)
60+
- [x] [Bit Hacks — Part 5 (Find absolute value of an integer without branching)](http://www.techiedelight.com/bit-hacks-part-5-find-absolute-value-integer-without-branching/)
6161
- [ ] [Bit Hacks — Part 6 (Random Problems)](http://www.techiedelight.com/bit-hacks-part-6-random-problems/)
6262

6363
## Algorithms
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package binary.absoluteCalculator;
2+
3+
import utils.InputReader;
4+
5+
// Given an integer, compute its absolute value (abs) without branching.
6+
public class AbsolutNumCalculator {
7+
8+
public static void main(String[] args) {
9+
System.out.println("Provide input number: ");
10+
int input = InputReader.readInt();
11+
System.out.println("No branching: " + absoluteNoBranch(input));
12+
System.out.println("Yes branching: " + absoluteYesBranch(input));
13+
}
14+
15+
private static int absoluteNoBranch(int x) {
16+
final int mask = x >> 31; // correct for 32-bit int
17+
return ((x + mask) ^ mask);
18+
// Explanation:
19+
// mask = x >> 31 gives:
20+
// 0 if x ≥ 0
21+
// -1 (all 1s) if x < 0 (in two's complement)
22+
// Then:
23+
// x + mask subtracts 1 from x if mask == -1
24+
// XOR with mask flips bits if mask == -1
25+
// Equivalent to x >= 0 ? x : -x
26+
}
27+
28+
private static int absoluteYesBranch(int n) {
29+
return ((n >> 31) & 1) == 1 ? -n : n; // ((n >> 31) & 1) ? (~n + 1) : n;
30+
// Explanation:
31+
// 1. shift 31 bits: keep sign bit (leftmost)
32+
// that's 0 for even nums and 1 for odd ones
33+
// 2. masking with 1
34+
// (0 for positives, 1s from two's complement for negatives)
35+
// 3. AND 1 to extract the least significant bit
36+
// If n >= 0, (n >> 31) is 0, so (n >> 31) & 1 = 0.
37+
// If n < 0, (n >> 31) is -1 (binary 111...111), so (n >> 31) & 1 = 1.
38+
}
39+
}

0 commit comments

Comments
 (0)