Java Solutions for Problems
Problem 1: Missing Number
import java.util.*;
class MissingNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int sum = n * (n + 1) / 2;
int arrSum = 0;
for (int i = 0; i < n - 1; i++) arrSum += sc.nextInt();
System.out.println(sum - arrSum);
}
}
Problem 2: Palindrome Check
import java.util.*;
class Palindrome {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
String rev = new StringBuilder(s).reverse().toString();
System.out.println(s.equals(rev) ? "Yes" : "No");
}
}
Problem 3: Fibonacci Series
import java.util.*;
class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner(System(System.in);
int n = sc.nextInt();
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int c = a + b;
a = b;
b = c;
}
}
}
Problem 4: Middle Element of Linked List
import java.util.*;
class MiddleLinkedList {
static class Node {
int data; Node next;
Node(int d) { data = d; }
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Node head = new Node(sc.nextInt());
Node temp = head;
for (int i = 1; i < n; i++) {
temp.next = new Node(sc.nextInt());
temp = temp.next;
}
Node slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
System.out.println(slow.data);
}
}
Problem 5: Binary Search
import java.util.*;
class BinarySearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) arr[i] = sc.nextInt();
int key = sc.nextInt();
int l = 0, r = n - 1, ans = -1;
while (l <= r) {
int mid = (l + r) / 2;
if (arr[mid] == key) { ans = mid; break; }
if (arr[mid] < key) l = mid + 1;
else r = mid - 1;
}
System.out.println(ans);
}
}
Problem 6: Count Vowels and Consonants
import java.util.*;
class VowelConsonant {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next().toLowerCase();
int v = 0, c = 0;
for (char ch : s.toCharArray()) {
if ("aeiou".indexOf(ch) != -1) v++;
else if (Character.isLetter(ch)) c++;
}
System.out.println(v + " " + c);
}
}