|
| 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