leetcode 299. Bulls and Cows

Orignal question can be found here.

My solution is as follows:

        unsigned int secret_len = strlen(secret), guess_len = strlen(guess);
        unsigned int acnt = 0, bcnt = 0;
        int* guess_flag = (int*)malloc(sizeof(int)*guess_len);
        int* secret_flag = (int*)malloc(sizeof(int)*secret_len);
        char* result = (char*)malloc(sizeof(char)*16);
        int i = 0, j = 0;

        for(i=0; i<guess_len; ++i)
                guess_flag[i] = 0;
        for(i=0; i<secret_len; ++i)
                secret_flag[i] = 0;

        i = 0;
        while(i<secret_len && i<guess_len)
        {
                if(secret[i] == guess[i])
                {
                        ++acnt;
                        guess_flag[i]=1;
                        secret_flag[i]=1;
                }
                ++i;
        }

        for(i=0; i<guess_len; ++i)
        {
                if(guess_flag[i] == 1)
                        continue;
                for(j=0; j<secret_len; ++j)
                {
                        if(guess[i] == secret[j] && secret_flag[j] == 0)
                        {
                                ++bcnt;
                                secret_flag[j]=1;
                                break;
                        }
                }
        }

        free(guess_flag);
        free(secret_flag);

        sprintf(result,"%dA%dB",acnt,bcnt);
        return result;

leetcode 342. Power of Four

Original question can be found here.

My solution is as follows:

bool isPowerOfFour(int num)
{
        if(num < 1)
                return false;
        if(num == 1)
                return true;
        if(num%4 != 0)
                return false;
        else
                return isPowerOfFour(num/4);
}

Actually, there is a better, O(1) solution:

bool isPowerOfFour(int n) 
{
    return !(n&(n-1)) && (n&0x55555555);
    //check the 1-bit location;
}

For more imformation, click here.

leetcode 345. Reverse Vowels of a String

Original question can be found here.

My solution is as follows:

int isVowels(const char c);

char* reverseVowels(char* s)
{
        int len=strlen(s);
        int i=0, j=len-1;
        char tmp;
        while(1)
        {
                while(!isVowels(s[i]) && i<len)
                        ++i;

                while(!isVowels(s[j]) && j>=0)
                        --j;
                if(i<j)
                {
                        tmp=s[i];
                        s[i]=s[j];
                        s[j]=tmp;
                        ++i;
                        --j;
                }
                else
                        break;
        }
        return s;
}

int isVowels(const char c)
{
        if(c=='a' || c=='o' || c=='e' || c=='i' || c=='u' || c=='A' || c=='O' || c=='E' || c=='I' || c=='U')
                return 1;
        return 0;
}