1. Reverse a string.
String str = "hello";
String rev = "";
for (int i = [Link]() - 1; i >= 0; i--) {
rev += [Link](i);
}
[Link](rev);
2. Check if a string is a palindrome.
String str = "madam";
boolean isPalindrome = true;
for (int i = 0; i < [Link]() / 2; i++) {
if ([Link](i) != [Link]([Link]() - 1 - i)) {
isPalindrome = false;
break;
}
}
[Link](isPalindrome);
3. Print Fibonacci series up to N terms.
int n = 10, a = 0, b = 1;
for (int i = 1; i <= n; i++) {
[Link](a + " ");
int sum = a + b;
a = b;
b = sum;
}
4. Check if a number is prime.
int num = 7;
boolean isPrime = num > 1;
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
[Link](isPrime);
5. Find factorial of a number.
int num = 5;
int fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
[Link](fact);
6. Find the largest element in an array.
int[] arr = {4, 2, 7, 1};
int max = arr[0];
for (int i = 1; i < [Link]; i++) {
if (arr[i] > max) max = arr[i];
}
[Link](max);
7. Find the second largest element in an array.
int[] arr = {4, 2, 7, 1};
int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int i = 0; i < [Link]; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
[Link](second);
8. Count vowels and consonants in a string.
String str = "hello";
int vowels = 0, consonants = 0;
for (int i = 0; i < [Link](); i++) {
char ch = [Link](i);
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z') {
if ("aeiouAEIOU".indexOf(ch) != -1) vowels++;
else consonants++;
}
}
[Link]("Vowels: " + vowels + ", Consonants: " + consonants);
9. Reverse an integer.
int num = 1234, rev = 0;
while (num != 0) {
rev = rev * 10 + num % 10;
num /= 10;
}
[Link](rev);
10. Check if two strings are anagrams.
String a = "listen", b = "silent";
if ([Link]() != [Link]()) {
[Link]("Not Anagram");
} else {
int[] count = new int[256];
for (int i = 0; i < [Link](); i++) {
count[[Link](i)]++;
count[[Link](i)]--;
}
boolean isAnagram = true;
for (int i = 0; i < 256; i++) {
if (count[i] != 0) {
isAnagram = false;
break;
}
}
[Link](isAnagram ? "Anagram" : "Not Anagram");
}