Detect Circular Pattern Match

Code

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

uint8_t is_circular_match(uint16_t reg, uint16_t target) {
    // If they are already equal, it's an immediate match (0 rotations)
    if(reg == target) return 1;

    // Rotate Left by 1 bit
    // (reg << 1) gets the left shift
    // (reg >> 15) gets the bit that fell off the left and moves it to the far right
    for(int i=1; i<16; i++)
    {
        reg = ((uint16_t)(reg << 1) | (reg >> 15));
        if(reg == target) return 1;
    }
    return 0;
}

int main() {
    uint16_t reg, target;
    scanf("%hu %hu", &reg, &target);
    printf("%hhu", is_circular_match(reg, target));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

45056 11

Expected Output

1