MCPcopy Create free account
hub / github.com/careercup/ctci / getMax

Method getMax

java/Chapter 17/Question17_4/Question.java:20–38  ·  view source on GitHub ↗
(int a, int b)

Source from the content-addressed store, hash-verified

18 }
19
20 public static int getMax(int a, int b) {
21 int c = a - b;
22
23 int sa = sign(a); // if a >= 0, then 1 else 0
24 int sb = sign(b); // if b >= 0, then 1 else 0
25 int sc = sign(c); // depends on whether or not a - b overflows
26
27 /* We want to define a value k which is 1 if a > b and 0 if a < b.
28 * (if a = b, it doesn't matter what value k is) */
29
30 int use_sign_of_a = sa ^ sb; // If a and b have different signs, then k = sign(a)
31 int use_sign_of_c = flip(sa ^ sb); // If a and b have the same sign, then k = sign(a - b)
32
33 /* We can't use a comparison operator, but we can multiply values by 1 or 0 */
34 int k = use_sign_of_a * sa + use_sign_of_c * sc;
35 int q = flip(k); // opposite of k
36
37 return a * k + b * q;
38 }
39
40 public static void main(String[] args) {
41 int a = 26;

Callers 1

mainMethod · 0.95

Calls 2

signMethod · 0.95
flipMethod · 0.95

Tested by

no test coverage detected