C language exercise - find a single dog problem

Finding Singles Questions

topic description

  • Find single dog questions:
  • 1. There is an array, only one element appears only once, and other elements appear twice, please find this element.
  • 2. If there are two elements in the array that appear only once and other elements appear twice, please find these two elements.

Code

#include <stdio.h>
#include <stdlib.h>

int FindOneSingleDog(int arr[], int size)
{
    
    
	int Dog = arr[0];
	for (int i = 0; i < size; i++)
	{
    
    
		Dog = Dog ^ arr[i];
	}
	return Dog;
}

int FindTwoSingleDog(int arr[], int size, int* Dog1, int* Dog2)
{
    
    
	int rst = arr[0];
	int leftPos = 0;

	for (int i = 1; i < size; i++)
	{
    
    
		rst = rst ^ arr[i];
	}
	for (leftPos = 0; leftPos < 32; leftPos++)
	{
    
    
		if ((rst & (1 << leftPos)) == 1)
		{
    
    
			break;
		}
	}

	*Dog1 = 0;
	*Dog2 = 0;

	for (int i = 0; i < size; i++)
	{
    
    
		if ((arr[i] & (1 << leftPos)) == 1)
		{
    
    
			*Dog1 = *Dog1 ^ arr[i];
		}
		else
		{
    
    
			*Dog2 = *Dog2 ^ arr[i];
		}
	}
	return 0;
}

int main()
{
    
    
	int arr1[] = {
    
     1,2,3,3,2,1,4 };
	int size1 = sizeof(arr1) / sizeof(arr1[0]);
	int Dog{
    
    };

	int arr2[] = {
    
     1,1,2,2,3,3,4,5 };
	int size2 = sizeof(arr2) / sizeof(arr2[0]);
	int Dog1{
    
    }, Dog2{
    
    };

	Dog = FindOneSingleDog(arr1, size1);
	printf("The One Single Dog Is: %d.\n", Dog);

	FindTwoSingleDog(arr2, size2, &Dog1, &Dog2);
	printf("The Two Single Dog Is: %d And %d.\n", Dog1, Dog2);

	system("pause");
	return 0;
}

Debug results

insert image description here

Guess you like

Origin blog.csdn.net/qq_45902301/article/details/125700388