###### tags: `learning` `zxm` # Ask zxm: LeetCode #371 Sum of Two Integers https://leetcode.com/problems/sum-of-two-integers/ ## Success ```cpp= int getSum(int a, int b){ int carry; // 64-bit while (b != 0) { carry = a & b; a = a ^ b; b = (carry & 0xFFFFFFFF) << 1; // limited to 32 bits } return a; } ``` ## Failure ```cpp= int getSum(int a, int b){ int carry; // 64-bit while (b != 0) { carry = a & b; a = a ^ b; b = (carry << 1); } return a; } ``` :::danger Runtime Error Line 7: Char 25: runtime error: left shift of negative value -2147483648 (solution.c) ::: :::danger Last executed input -1 1 ::: -2147483648 is 10000000000000000000000000000000 LeetCode is saying a left-shift to 10000000000000000000000000000000 is incorrect. ## Question 0 Why do I have to add `& 0xFFFFFFFF`? In fact, the version without `& 0xFFFFFFFF` ```cpp= int getSum(int a, int b){ int carry; // 64-bit while (b != 0) { carry = a & b; a = a ^ b; b = (carry << 1); } return a; } ``` will work in https://www.onlinegdb.com/online_c_compiler and https://www.jdoodle.com/c-online-compiler I didn't find deference between using `& 0xFFFFFFFF` or not when I printed everything linewise on the above two website, by the code below. ```cpp= #include <stdio.h> void print2(int x) { for (int c = 31; c >= 0; c--) { int k = x >> c; if (k & 1) printf("1"); else printf("0"); } printf("\n"); } int getSum(int a, int b){ int direct_sum_without_carry = a ^ b; // XOR printf("before the while; XOR; direct_sum_without_carry %d\n", direct_sum_without_carry); print2(direct_sum_without_carry); int carry = a & b; // AND printf("before the while; AND; carry %d\n", carry); print2(carry); while (carry != 0){ a = direct_sum_without_carry; //b = carry << 1; b = (carry & 0xFFFFFFFF) << 1; direct_sum_without_carry = a ^ b; // XOR printf(" direct_sum_without_carry %12d ", direct_sum_without_carry); print2(direct_sum_without_carry); carry = a & b; // AND printf(" carry %12d ", carry); print2(carry); } int direct_sum_with_all_carry = direct_sum_without_carry; return direct_sum_with_all_carry; } int main() { int a = -1; int b = 1; printf("%d\n", getSum(a,b)); return 0; } ``` ## Question 1 Why there are 32 bits (8 bytes)? I have used `sizeof(int)` and got `4` on Leetcode and those online compiler.