Pure C language solution


  • 0
    L

    #include <stdio.h>
    #include <string.h>
    #include <malloc.h>

    void setCharcter(char *p, int *index, int num);
    void setCharcter(char *p, int *index, int num)
    {
    int i, j;
    char a[10] = {0};

    i = 0;
    do
    {
    	a[i++] = num % 10;
    	num /= 10;
    } while (num != 0);
    
    for (j = i - 1; j >= 0; j--)
    {
    	p[(*index)++] = a[j] + '0';
    }
    

    }

    char* getHint(char* secret, char* guess)
    {

    int nums1[10] = {0};
    int nums2[10] = {0};
    
    int bulls = 0;
    int cows = 0;
    
    int i = 0;
    char *s   = (char*)calloc(20, sizeof(char*));
    char temp[10] = "";
    
    while (guess[i] != '\0')
    {
    	if (guess[i] == secret[i])
    	{
    		bulls ++;
    	}
    	else
    	{
    		nums1[guess[i] - '0'] ++;
    		nums2[secret[i] - '0'] ++;
    	}
    
    	i++;
    }
    
    for (i = 0; i < 10; i++)
    {
    
    	cows += (nums1[i] > nums2[i]) ? (nums2[i]) : (nums1[i])  ;
    }
    
    i = 0;
    setCharcter(s, &i, bulls);
    s[i++] = 'A';
    setCharcter(s, &i, cows);
    s[i++] = 'B';
    s[i] = '\0';
    
    return s;
    

    }

    void main(void)
    {
    char a[30] = "00112233445566778899";
    char b[30] = "16872590340158679432";

    puts(getHint(a, b));
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.