Don't know how to fix the runtime error, my code is in c


  • 0
    G

    Here is my code, I am getting runtime errors. I am not sure how should I format my return string. Is the input always going to be 4 digits?

     char* getHint(char* secret, char* guess) {
      int i = 0;
      int countbull = 0;
      int countcow = 0;
      char numsecret[10] = {0};
      char numguess[10] = {0};
      static char result[4] = {0,'A',0, 'B' };
      
      //count bulls
      for (i = 0; i < 4; i++)
        {
          if (secret[i] == guess[i])
    	{
    	  countbull++;
    	}
          //record numbers
          numsecret[secret[i] - 48]++;
          numguess[guess[i] - 48]++;
        }
      
      //count cows
      for (i = 0; i < 10; i++)
        {
          //printf("numsecret[%d] = %d ", i, numsecret[i]);
          //printf("numguess[%d] = %d \n", i, numguess[i]);
          if (numsecret[i] <= numguess[i])
    	{
    	  countcow += numsecret[i];
    	}
          else
    	{
    	  countcow += numguess[i];
    	}
        }
      countcow -= countbull;
      //printf("%d, %d\n", countbull, countcow);
      result[0] = countbull + 48;
      result[2] = countcow + 48;
      return result;
    }

  • 0

    Hello, the length of the input strings can be longer than 4. By the way, why do you define the result as a static variable?


  • 0
    D
    public class Solution {
    public String getHint(String secret, String guess) {
        int bull = 0, cow = 0;
        int[] array = new int[10];
        
        for(int i = 0; i < secret.length(); i++) {
            char s = secret.charAt(i);
            char g = guess.charAt(i);
            if(s == g){
                bull++;
            }else {
                if(array[s - '0'] < 0) {
                    cow++;
                }
                array[s - '0']++;
                
                if(array[g - '0'] > 0) {
                    cow++;
                }
                array[g -'0']--;
            }
        }
        return bull + "A" + cow + "B";
    }
    

    }


Log in to reply
 

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