Anyways, here are a few very simple algoz questions typically asked during interviews and their answers -
1) Write a program to find the factorial (e.g. fact(4) = 4*3*2*1) of a number.
Ans. Recursion.
public class Factorial {
public long fact(int number) {
if (number == 1) {
return number;
}
return number * fact(number - 1);
}
public static void main(String[] args) {
System.out.println(new Factorial().fact(3));
}
}
2] Write a program to reverse a string without using for,while constructs.
Ans. Recursion again.
public class StringReverse {
public String reverse(String str) {
if (str.length() == 1) {
return str;
}
return str.charAt(str.length() - 1) + "" + reverse(str.substring(0, str.length() - 1));
}
public static void main(String[] args) {
System.out.println(new StringReverse().reverse("abcdef"));
}
}3] Write a program to count the number of digits present in an int.
public class CountDigits {
private static int count(int number) {
int count = 0;
while (number != 0) {
number /= 10;
count ++;
}
return count;
}
public static void main(String[] args) {
System.out.println(count(1000));
}
}
4] Same as above without using a for,while loop.
Ans. Recursion.
public class CountDigits2 {
private static int count = 0;
public static int count(int number) {
if (number == 0)
return count;
count++;
return count(number/10);
}
public static void main(String[] args) {
System.out.println(count(12345));
}
}
5] Write a program to reverse an int.
public class ReverseInt {
private static int reverseInt(int number) {
int reversed_number = 0;
while (number != 0) {
reversed_number = reversed_number * 10 + (number % 10);
number /= 10;
}
return reversed_number;
}
public static void main(String[] args) {
System.out.println(reverseInt(12345));
}
}
6] Write a program to find the 2nd max of an int array.
public class SecondMax {
private static int getSecondMax(int[] elements) {
int max1 = elements[0];
int max2 = elements[0];
for (int i=1;iif (elements[i] > max1) {
max2 = max1;
max1 = elements[i];
}
}
return max2;
}
public static void main(String[] args) {
int[] elements = {5,6,6,6,2,3,1,1,0};
System.out.println(getSecondMax(elements));
}
}
7] Write a program which has 2 threads sharing an int array containing numbers from 1 to 10.One thread should print the array elements from the beginning to the end and the other thread should print the elements from the end to the beginning of the shared array such that each print is of alternate thread.
e.g. if elements = {1,2,3,4,5} and there are 2 threads T1(which prints from 0 to length-1) and T2(which prints from length-1 to 0).Then the output should be as follows -
T1 prints> 1
T2 prints> 5
T1 prints> 2
T2 prints> 4
....
....
...
Ans. The following code does the above -

1 comment:
The algorithm looks good. I have one question here...
What happens if for some reason one of the thread abruptly terminates? The other thread will never terminate ain't it?
Should we handle that?
-Srinivas
Post a Comment