Web Toolbar by Wibiya

Pages

Wednesday, October 26, 2011

Given an integer n, write code to calculate n+1, without using +,-,++,--,*,/

Solution# 1: Start from the LSB and keep setting them to 0 till we find the first 0. And then set that 0 to 1. Here is the code,

#include 
#include 

int increment(int n)
{
    int i = 1;

    while(i&n)
    {
        n = n & ~i;
        i = i<<1;
    }

    return n|i;
}

int main()
{
    printf("%d\n", increment(5));
    return 0;
}

Tuesday, October 25, 2011

Write an algorithm to find the number of ways of placing 3 balls in 3 buckets. Bucket 1 can hold 2 balls, bucket 2 can hold 3 balls and bucket 3 can hold 2 balls..

Solution# 1: We can try all the permutations using the following code,
#include 
#include 

int main()
{
    int A;
    int B;
    int C;
    int count=0;

    for(A=0;A<=2;A++)
    {
        for(B=0;B<=3;B++)
        {
            for(C=0;C<=2;C++)
            {
                    if((A+B+C)==3)
                    {
                        printf("%d%d%d\n", A, B, C);
                        count++;
                    }
            }
        }
    }
    printf("count = %d\n", count);
    return 0;
}

Sunday, October 23, 2011

Given a string, print all possible uppercase and lowercase permutations of it.

Solution #1: This can be easily solved by recursion. Fix one letter to either uppercase or lowercase and permute rest of the letters. Here is the code,

#include 
#include 
#include 
#include 

void toggle(char* str, int n)
{
    if(n == strlen(str))
    {
        printf("%s\n", str);
        return;
    }

    str[n] = toupper(str[n]);
    toggle(str, n+1);
    str[n] = tolower(str[n]);
    toggle(str, n+1);
}

int main()
{
    char str[50] = {0, };

    sprintf(str, "suchit maindola");

    toggle(str, 0);

    return 1;
}