All submissions

Identify Trap in Signed vs Unsigned Comparison

Code

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

int safe_compare(int8_t a, uint8_t b) {
    // Your logic here
    if (a & 80) 
        return 1;

    if (b & 0x80)
        return 1;

    if (a < b) 
        return 1; 
    return 0;
}

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

Solving Approach

 

if a is negative then a is less than b.

if msb of b is 1, then b is > a;

otherwise if a is positive and b doesn't have 1 as msb then straight compare

 

Loading...

Input

-1 1

Expected Output

1