Java Interview Guide: How to Build Confidence With a Solid Understanding of Core Java Principles pdfdrive com



Yüklə 0,53 Mb.
Pdf görüntüsü
səhifə39/47
tarix06.05.2023
ölçüsü0,53 Mb.
#108601
1   ...   35   36   37   38   39   40   41   42   ...   47
Java Interview Guide

Programming Problems
How to Approach Programming Problems
During the interview you may be asked to solve high-level programming
problems. In order to demonstrate a healthy approach to problem solving, follow
these steps:
1. Restate the problem to ensure that you understand it correctly.
2. Provide a simple solution regardless of efficiency.
3. Critique your solution and analyze it for optimizations.
Identifying the nature of a problem can help you solve it. For example, problems
that require repetitive steps lend themselves well to recursion. Problems
involving collections of data often utilize existing data structures. Practice
solving sample problems and study the process of discovering a solution rather
than memorizing the solution itself.


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.

Yüklə 0,53 Mb.

Dostları ilə paylaş:
1   ...   35   36   37   38   39   40   41   42   ...   47




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin