All submissions

Add Signed and Unsigned Integers Safely

Approach and Code

#include <stdio.h>
#include <stdint.h>
/*
inputs -> signed and unsigned ints 8 bit
output -> signed int 16 bit

int8 (-128 to 127)
uint8 (0 to 255)

Edge cases:
- a is negative and b is large, the result should be correct and not a wrap around
- when both the inputs are at max/min, the result should not overflow

Plan:
- typecast a & b to int16
- add them
- return the result as int16
*/



int16_t signed_unsigned_sum(int8_t a, uint8_t b) {
    // Your logic here
    int16_t sum = 0;
    sum = (int16_t)a + (int16_t)b;
    return sum;
}

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

Solving Approach

 

 

 

Loading...

Input

-10 20

Expected Output

10