Share via


Once I was a College Student

<re-published from my old blog>

So there I was, sitting at my desk staring at the computer screen working on VS 2010 and exploring a bit of F#. I just sat back and started reflecting on my college days and the interviewing season in the 7th semester. All of us, revising all our technical knowledge, solving puzzles and complex analytical problems.
As I think about it now, I think that those problems (especially the programming ones) were pretty easy ones, but in that period, preparing for your first tryst with the world outside, its a huge thing. So, feeling a little nostalgic, I thought I’ll rewrite some of those programs in C# this time.

1. How to swap two numbers without using a third variable.
    public class SwapperClass
    {
        public static void Main()
        {
            int number1 = 10;
            int number2 = 20;

Console.WriteLine("a = {0}, b={1}", number1, number2);

Swap(ref number1, ref number2);

Console.WriteLine("a = {0}, b={1}", number1, number2);
            Console.ReadLine();
        }
 
        public static void Swap(ref int a, ref int b)
        {
            a = a + b;
            b = a - b;
            a = a - b;
        }
    }

2. How to find out whether a number is a power of 2 or not in O(1) or without using any loops
public class PowerOfTwo
    {
        public static void Main()
        {
            Console.WriteLine(IsPowerOfTwo(4));
            Console.ReadKey();
        }
 
        public static bool IsPowerOfTwo(int a)
        {
            return (a != 0 && (a & (a - 1)) == 0);
        }
    }

Till my next post,

Regards,

 

AlD