Add Signed and Unsigned Integers Safely

Code

#include <stdio.h>
#include <stdint.h>

int16_t signed_unsigned_sum(int8_t a, uint8_t b) {
    // Your logic here
    int16_t result = 0U;
    if (a >= 0) {
        // add two positive
        result = (uint8_t)a + b;
        if ( ( uint8_t )a > ( 0xFF - b ) ) {
            result |= (1 << 16); 
        }
    } else {
        // subtract a 
        uint8_t new_a = (~a) + 1;
        if (new_a <= b) {
            result = b - new_a;
        } else {
            result = new_a - b;
            result |= (1 << 16); 
        }
    }
    return result;
}

int main() {
    int8_t a;
    uint8_t b;
    scanf("%hhd %hhu", &a, &b);
    printf("%d", signed_unsigned_sum(a, b));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

-10 20

Expected Output

10