Finding MAX of numbers without conditional IF statements c++ -
this question has answer here:
so have 2 numbers user input, , find max of 2 numbers without using if statements.
the class beginner class, , have use know. kinda worked out, works if numbers inputted max number first.
#include <iostream> using namespace std; int main() { int x = 0, y = 0, max = 0; int smallest, largest; cout << "please enter 2 integer numbers, , show 1 larger: "; cin >> x >> y; smallest = (x < y == 1) + (x - 1); smallest = (y < x == 1) + (y - 1); largest = (x < y == 1) + (y - 1); largest = (y > x == 1) + (x + 1 - 1); cout << "smallest: " << smallest << endl; cout << "largest: " << largest << endl; return 0; }
thats have far, after putting different test data in, found out works numbers such 4,5 or 6,7. numbers more 2 spaces between eachother dont such as, 4,8 or 5, 7. appreciated.
i saw question in cracking coding interview book.
let’s try solve “re-wording” problem re-word problem until has removed if statements
rewording 1: if > b, return a; else, return b
rewording 2: if (a - b) negative, return b; else, return a
rewording 3: if (a - b) negative, let k = 1; else, let k = 0 return - k * (a - b)
rewording 4: let c = - b let k = significant bit of c return - k * c
int getmax(int a, int b) { int c = - b; int k = (c >> ((sizeof(int) * char_bit) - 1)) & 0x1; int max = - k * c; return max; }
source: http://www.amazon.com/cracking-coding-interview-programming-questions/dp/098478280x
edit: code works when a-b overflows. let k equal sign of a-b such if a-b >=0, k 1, else k=0.let q inverse of k. above code overflows when positive or b negative, or other way around. if , b have different signs, want k equal sign(a).
/* flips 1 0 , vice-versa */ public static int flip(int bit){ return 1^bit; } /* returns 1 if positive, , 0 if negative */ public static int sign(int a){ return flip((a >> ((sizeof(int) * char_bit) - 1)) & 0x1); } public static int getmax(int a, int b){ int c = - b; int sa = sign(a-b); // if a>=0, 1 else 0 int sb = sign(a-b); // if b>=1, 1 else 0 int sc = sign(c); // depends on whether or not a-b overflows /* if , b have different signs, k = sign(a) */ int use_sign_of_a = sa ^ sb; /* if , b have same sign, 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 * k + b * q; }
Comments
Post a Comment