Create method which checks if x + y will overflow using bitwise operations
问题 I need to create a method in C using bitwise operations which checks if x + y will overflow or not. I can only use a maximum of 20 of the following operations; ! ~ & ^ | + << >> Keep in mind I have to test for both negative and positive numbers. I've tried several times to make it work. Is my logic sound? I'm going by: if (x + y) is less than x, then it has overflowed. Based on that logic, I wrote this; int addOK(int x, int y) { int sum = x + y; int nx = ((~x) + 1); int check = (sum + nx)>>31