forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbsWithoutBranching.java
More file actions
37 lines (34 loc) · 817 Bytes
/
AbsWithoutBranching.java
File metadata and controls
37 lines (34 loc) · 817 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.rampatra.bits;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 6/9/15
* @time: 12:26 PM
*/
public class AbsWithoutBranching {
/**
* Returns the absolute value of any integer.
* <p/>
* EXPLANATION:
* For example, consider int takes 4 bits:
* So for input = -5, we have
* -5 = 1011
* mask = 1111
* mask + n = 1010
* (mask + n)^mask = 0101 (which is 5)
*
* @param n
* @return
*/
public static int abs(int n) {
int mask = n >> 31;
return (mask + n) ^ mask;
}
public static void main(String[] args) {
System.out.println(abs(-5));
System.out.println(abs(5));
System.out.println(abs(0));
System.out.println(abs(-0));
}
}