Factorial!

Getting this question for a whiteboard problem is fun. It allows you to give your interviewer a second long “Are you serious?” look and then turning to the white-board and knocking it out in silence. Of course if you get it wrong you get to wish that you can just melt into the carpet.

The factorial of a number is simply a number multiplied by each integer smaller than itself, all the way down to 1.


public static int factorial(int number){

    if (number < 1){
        return 0;
    }

    int fact = 1;
    for(int i=number; i>0; i--){
        fact=fact*i;
    }

    return fact;

}

Of course, you will probably be asked if you can do this recursively too, so you turn around and and scribble this on the white-board


public static int factorial(int number){

    if (number < 1){
        return 0;
    }

    if (number==1){
        return 1;
    }

    return number*factorial(number-1);

}

Palindrome Test

The palindrome tester is another white-board favorite for interviewees. For those that do not know, a palindrome is any sequence of characters and/or numbers that is the same read forwards or backwards. BOB is a palindrome since BOB is BOB backwards. Get it? Got it? Good!

So, the easiest way of checking if a given string is a palindrome, is to reverse it and check it against the original. As usual, there are a whole bunch of ways to solve this. This solution is the easiest I can think of.

public static void main(String[] args) {

  String input = args[0];

  String reversed = "";

  for (int i = input.length()-1; i&gt;=0; i--)
  {
    reversed += input.charAt(i);
  }

  if (input.equals(reversed))
  {
    System.out.println("Palindrome!");
  }
  else
  {
    System.out.println("NON Palindrome!");
  }
}

Fizz-Buzz

It seems that in every interview ever, this question has been asked :

Print out all the numbers between 1 and 100. If a number is divisible by 3, print “fizz” next to it. If a number is divisible by 5, print “buzz” next to it. If it is divisible by both, print “fizzbuzz” next to it.

Naturally there are many solutions to this problem. I will give my first gut-feel solution here.


public static void main(String[] args) {
 
     for (int i=0; i &amp;lt;= 100; i++){
         System.out.print(i + " ");
         if (i%3 == 0){
             System.out.print("Fizz");
         }
         if (i%5 == 0)
         {
            System.out.print("Buzz");
         }
         System.out.println();
     }
 }