All submissions

Detect Underflow in Unsigned Subtraction

Code

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

void subtract_with_underflow(uint8_t a, uint8_t b, uint8_t *diff, uint8_t *carry) {
    // Write logic here
    // Edge case
    if( a == 0 && b == 0)
    {
        *diff = 0;
        *carry = 0;
    }

    if(a > b)
    {
        *diff = a - b;
        *carry = 0;
    }
    else
    {
        if( a < b)
        {
            *diff = a - b;
            *carry = 1;
        }
    }
}

int main() {
    uint8_t a, b, diff, carry;
    scanf("%hhu %hhu", &a, &b);
    subtract_with_underflow(a, b, &diff, &carry);
    printf("diff = %u, carry = %u", diff, carry);
    return 0;
}

Solving Approach

Plan:
- if a > b then *diff = a - b; *carry = 0;
- if a < b then *diff = a - b ; *carry = 1
- if a & b both are 0 then *diff = 0 & *carry = 0

 

 

Loading...

Input

100 50

Expected Output

diff = 50, carry = 0