medium
1 views

Function samePositionBitCount – CTS PATTERN

Count the number of positions where two integers have equal bits

Understand the Problem

Problem Statement

You are required to fix all logical errors in the given code. The function samePositionBitCount(int N1, int N2) accepts two integers N1 and N2 as input. The function should return the count of bits which are equal in both integers at the same bit positions.

For example, if N1 = 5 (binary: 101) and N2 = 3 (binary: 011), the bits are equal at the second position (both have 0), so the function should return 1.

Constraints

  • Input integers N1 and N2 can be any valid 32-bit signed integers
  • The function must handle negative numbers correctly
  • Bit positions are compared from LSB to MSB
  • Time complexity should be O(log(max(N1, N2)))
  • Space complexity should be O(1)

Examples

Example 1
Input
N1 = 5, N2 = 3
Output
1
Explanation

Binary of 5 is 101, binary of 3 is 011. Only the second bit position (from right, 0-indexed) has the same value (0), so count is 1.

Example 2
Input
N1 = 7, N2 = 15
Output
3
Explanation

Binary of 7 is 0111, binary of 15 is 1111. The last three bit positions have the same values (all 1s), so count is 3.

Example 3
Input
N1 = 8, N2 = 2
Output
0
Explanation

Binary of 8 is 1000, binary of 2 is 0010. No bit positions have the same values, so count is 0.

Solution

#include <stdio.h>

int samePositionBitCount(int N1, int N2) {
    int count = 0;
    
    // Handle negative numbers by using unsigned conversion
    unsigned int num1 = (unsigned int)N1;
    unsigned int num2 = (unsigned int)N2;
    
    while (num1 > 0 || num2 > 0) {
        // Extract the least significant bit of both numbers
        int bit1 = num1 & 1;
        int bit2 = num2 & 1;
        
        // If bits are equal, increment count
        if (bit1 == bit2) {
            count++;
        }
        
        // Right shift both numbers to check next bit
        num1 >>= 1;
        num2 >>= 1;
    }
    
    return count;
}

// Test function to verify the solution
int main() {
    printf("Test 1: %d\n", samePositionBitCount(5, 3));   // Expected: 1
    printf("Test 2: %d\n", samePositionBitCount(7, 15));  // Expected: 3
    printf("Test 3: %d\n", samePositionBitCount(8, 2));   // Expected: 0
    return 0;
}
Time:O(log(max(N1, N2))) - The loop runs for the number of bits in the larger number
Space:O(1) - Only using a constant amount of extra space
Approach:

The C solution fixes the original code by:

  • Converting signed integers to unsigned to handle negative numbers correctly
  • Using bitwise AND with 1 (& 1) to extract the least significant bit instead of modulo
  • Using right shift (>>= 1) to move to the next bit position
  • Comparing extracted bits and counting matches
  • Continuing until both numbers become 0

This approach ensures proper bit-by-bit comparison for all integer values.

Visual Explanation

Loading diagram...