All submissions

Checksum Validation

Code

#include <stdio.h>

int validate_checksum(int *mem, int n) {
    // Write your XOR scan logic here
    int *ptr, i, result=0;

    ptr=mem;
    // skip the checksum byte
    for (i=0, ptr=mem; i < (n-1); i++, ptr++) { 
        result ^= *ptr; 
    }
    return ((result ^ *ptr) == 0 ? 1 : 0);
}

int main() {
    int n, arr[100];
    scanf("%d", &n);
    
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int result = validate_checksum(arr, n);
    printf("%d", result);

    return 0;
}

Solving Approach

set a pointer to the top, prepare to XOR everything. start with result = 0

XOR result with every element down to the (last -1)

at the same time increment i to control the count and increment the pointer.

when done with the elements of the array all XORed into result.

then XOR this with the last element which is the actual checksum

if the two are the same, the XOR will be zero and the answer is ONE 

if they're different the XOR will be non-zero and the answer is ZERO (as in incorrect)

 

 

 

Loading...

Input

5 10 20 30 40 60

Expected Output

0