Web Toolbar by Wibiya

Pages

Tuesday, February 28, 2012

Implement atoi().

Solution #1: Here is the code,

int my_atoi(char* str)
{
    int len = strlen(str);
    int i;
    int isNegative = 0;
    int num = 0;

    if(str[0] == '-')
    {
        isNegative = 1;
        str++;
    }

    for(i=0; i < len; i++)
    {
        int curr = str[i] - '0';

        //if it is a digit then put it at the units place
        if((curr >=0) && (curr <= 9))
        {
            num = num*10 + curr;
        }
        else //if not a digit then break
            break;
    }

    if(isNegative)
        num = num*-1;

    return num;
}

int main()
{
    printf("%d\n", my_atoi("-123"));
    return 0;
}

Find second maximum value in an array efficiently.

Solution #1: Sorting is one obvious way, but, there is another efficient way. Here is the code,

int secondMax(int* arr, int len)
{
    int max = 0;
    int sMax = 0;
    int i = 0;

    for(i=0; i < len; i++)
    {
        int curr = arr[i];

        if(curr > max)
        {
            sMax = max;
            max = curr;
        }
        else if(curr > sMax)
            sMax = curr;
    }

    return sMax;
}

int main()
{
    int arr[5] = {3, 2, 5, 1, 4};

    printf("Second Max: %d\n", secondMax(arr, 5));

    return 0;
}