Sample Programming Problems
How would you write a method that calculates the factorial of a number?
A factorial is the product of an integer and all of the integers below
it (4! = 4*3*2*1). A factorial is a
naturally recursive operation, which is
apparent if you visualize the formula as part of the solution (4 * 3!).
The formula can then be converted into a recursive method call:
n * factorial(n - 1)
. However, the first line in a recursive algorithm
should define a termination condition. Here, an input of 1 requires no recursion
because the result is simply 1.
Recursive methods are slower than loops due
to the overhead of method
invocations. A recursive method can be converted to an iterative method
by creating a loop that steps towards the termination condition and updates the
state of local variables. In practice, you should
always favor simplicity over
premature optimization, but in the context of an interview you should be as
critical as possible.
How would you determine whether a string is a palindrome?
A palindrome is a word that is identical forwards and backwards. A simple
solution is to reverse the string and compare it to the original.
There is no reverse
method in the String class, but you could use the
StringBuilder#reverse()
method or a recursive formula: hello =
o + reverse(hell)
.
Rather than create additional String instances, a more
efficient solution would
use the String#charAt() method with pointers on both ends converging
towards the middle of the string. If each character matches before the pointers
converge, the string is a palindrome.
Dostları ilə paylaş: