Saturday, June 4, 2011

Multiply a number by 7 without using * and + operator

int Num = n;
int NewNum;

NewNum = Num << 3; // mulitplied by 2 ^ 3 = 8

NewNum = NewNum - Num; // 8 – 1 = 7 if n = 1

Covert a string to upper case

void ToUpper(char * S)
{
while (*S!=0)
{
*S=(*S >= 'a' && *S <= 'z')?(*S-'a'+'A'):*S;
S++;
}

Reverse a string

void ReverseString (char *String)
{
char *Begin = String;
char *End = String + strlen(String) - 1;
char TempChar = '\0';

while (Begin < End)
{
TempChar = *Begin;
*Begin = *End;
*End = TempChar;
Begin++;
End--;
}
}

Puzzle 3: The 8 ball problem

The problem is quite simple. You are given 8 identical-looking balls, one of which is heavier than the other 7 (all of which weigh the same). Using an old-fashioned mechanical set of scales you must identify the heavier ball using the scale as few times as possible. The scale is constructed using two bowls and an arm enabling the bowls to either balance or have one bowl rising while the other (and heavier bowl) falling. You can't just add one ball at a time thinking its one weighing, however, you may put any number of balls in each bowl... All you need to solve the puzzle is to use a bit of common sense. 


Solution:


You can identify the heavier ball in only 2 weighings!!!! 
To achieve this in only 2 weighings, you first put 3 balls in each bowl on the scale, e.g. {1,2,3} against {4,5,6}. Should the scale balance, you have only 2 balls remaining which you can compare by putting each in a separate bowl on the scale, e.g. {7} against {8}. Should the scale not balance, however, take the 3 balls from the heavier bowl on the scale (e.g. 1,2,3). Pick any 2 balls and compare these against each other, e.g. {1} against {2}. If the scale balances, you know it is ball 3 is the heavier. Is the scale moving, you know it's the ball on the heavier side.

Puzzle 2 : 100 coins and 7 Bags


A dealer has 100 coins and only 7 money bags. He has to divide the coins over the seven bags so that he can make any number of coins simply by handing over a few bags. How must he divide the money over the seven money bags?

Solution:

Bag 1 = 01 ( 2^0 )
Bag 2 = 02 ( 2^1 )
Bag 3 = 04 ( 2^2 )
Bag 4 = 08 ( 2^3 )
Bag 5 = 16 ( 2^4 )
Bag 6 = 32 ( 2^5 )
Bag 7 = 37 ( 100 - ( 1 + 2 + 4 + 8 + 16 + 32 ) )

Now suppose some one ask for 1 coin he can give Bag 1, for 2 he can give Bag 2, for three he can give Bag 1+ Bag 2,....for 53 coins he can give Bag 6(32) + Bag 5(16) + Bag 3(4) +Bag 1(1) and so on...