Interview Questions - Tricky

interview-questions

Implements a function that output Fibonaci sequence:

``````<?php
function fib(\$i) {
if (\$i == 0) {
return 0;
} elseif (\$i == 1) {
return 1;
} else {
return fib(\$i - 1) + fib(\$i - 2);
}
}
for (\$i = 0; \$i < 10; \$i++) {
echo "\$i:" . fib(\$i) . "\n";
}
?>```
```

By definition, the first two numbers in the Fibonacci sequence are either 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two. The sequence Fn of Fibonacci numbers is defined by the recurrence relation: F_{n}=F_{n-1}+F_{n-2}, with seed values being:

• F_{1}=1 and F_{2}=1 or
• F_{0}=0 and F_{1}=1

Write code to display a number using its binary form:

``````public static void toBase(int number, int base) {
String binary = "";
int temp = number/2+1;
for (int j = 0; j < temp ; j++) {
try {
binary += "" + number % base;

number /= base;
} catch (Exception e) {
}
}
for (int j = binary.length() - 1; j >= 0; j--) {
System.out.print(binary.charAt(j));
}
}```
```

Write code to flip bits:

``````StringBuilder binary = new StringBuilder();
int n=15;
while (n > 0) {
if ((n&1)==1) {
binary.append(1);
} else {
binary.append(0);
}
n >>= 1;
}
System.out.println(binary.reverse());```
```

Write code to determine if a string is a palindrome:

``````// Possible solution:
public static boolean isPalindrome(String str) {