Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I saw this question in Cracking the Coding interview book.</p> <p>Let’s try to solve this by “re-wording” the problem We will re-word the problem until we get something that has removed all if statements</p> <p>Rewording 1: If a > b, return a; else, return b<br> Rewording 2: If (a - b) is negative, return b; else, return a<br> Rewording 3: If (a - b) is negative, let k = 1; else, let k = 0 Return a - k * (a - b) <br> Rewording 4: Let c = a - b Let k = the most significant bit of c Return a - k * c</p> <pre><code>int getMax(int a, int b) { int c = a - b; int k = (c &gt;&gt; ((sizeof(int) * CHAR_BIT) - 1)) &amp; 0x1; int max = a - k * c; return max; } </code></pre> <p>Source: <a href="http://rads.stackoverflow.com/amzn/click/098478280X" rel="nofollow">http://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X</a></p> <p>Edit: This code works even when a-b overflows. Let k equal the sign of a-b such that if a-b >=0, then k is 1, else k=0.Let q be the inverse of k. Above code overflows when a is positive or b is negative, or the other way around. If a and b have different signs, then we want the k to equal sign(a). </p> <pre><code>/* Flips 1 to 0 and vice-versa */ public static int flip(int bit){ return 1^bit; } /* returns 1 if a is positive, and 0 if a is negative */ public static int sign(int a){ return flip((a &gt;&gt; ((sizeof(int) * CHAR_BIT) - 1)) &amp; 0x1); } public static int getMax(int a, int b){ int c = a - b; int sa = sign(a-b); // if a&gt;=0, then 1 else 0 int sb = sign(a-b); // if b&gt;=1, then 1 else 0 int sc = sign(c); // depends on whether or not a-b overflows /* If a and b have different signs, then k = sign(a) */ int use_sign_of_a = sa ^ sb; /* If a and b have the same sign, then k = sign(a - b) */ int use_sign_of_c = flip(sa ^ sb); int k = use_sign_of_a * sa + use_sign_of_c * sc; int q = flip(k); //opposite of k return a * k + b * q; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload