Skip to content

RoopakCS/problem-solving-with-java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 

Repository files navigation

Problem Solving With Java

Reverse Number

import java.util.Scanner;

public class Reverse {

    public static void main(String[] args) {
        int num, rem, res = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        num = sc.nextInt();
        int temp = num;
        while (temp != 0) {
            rem = temp % 10;
            res = res * 10 + rem;
            temp /= 10;
        }
        System.out.println("The reversed number is: " + res);
        sc.close();
    }
}

Palindrome Or Not

import java.util.Scanner;

public class Palindrome {

    public static void main(String[] args) {
        int num, rem, res = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        num = sc.nextInt();
        while (res < num) {
            rem = num % 10;
            res = res * 10 + rem;
            num /= 10;
        }
        if (res == num || res / 10 == num) {
            System.out.println("It is a palindrome");
        } else {
            System.out.println("It is not a palindrome");
        }
        sc.close();
    }
}

Armstrong Number

import java.util.Scanner;

public class Armstrong {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num, temp, res = 0, rem, digit;

        System.out.print("Enter a number: ");

        num = sc.nextInt();
        temp = num;
        digit = (int) (Math.log10(num) + 1);
        while (temp > 0) {
            rem = temp % 10;
            res += Math.pow(rem, digit);
            temp /= 10;
        }
        if (res == num) {
            System.out.print(num + " is an armstrong number");
        } else {
            System.out.print(num + " is not an armstrong number");
        }
        sc.close();
    }
}

Perfect Number

import java.util.Scanner;

public class Perfect {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num, sum = 0;
        System.out.print("Enter a number: ");
        num = sc.nextInt();

        for (int i = 1; i <= (num / 2); i++) {
            if (num % i == 0) {
                sum += i;
            }
        }

        if (num == sum) {
            System.out.print(num + " is a perfect number");
        } else {
            System.out.print(num + " is not a perfect number");
        }
        sc.close();
    }
}

Cube Root

import java.util.Scanner;

public class CubeRoot {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        double num = sc.nextInt();
        double start = 1;
        double end = num;
        double mid;
        double ans = -1;

        while (start <= end) {
            mid = start + (end - start) / 2;
            double cube = mid * mid * mid;

            if (cube > num) {
                end = mid;
            } else if (cube < num) {
                start = mid;
            } else if (cube == num) {
                ans = mid;
                break;
            }
        }

        System.out.print("The cube root of " + (int)num + " is " + ans);
        sc.close();
    }
}

Prime Numbers

import java.util.Scanner;

public class Primes {

    public static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }

        for (int i = 2; i <= Math.sqrt(num); i++) {
            if (num % i == 0) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the start value: ");
        int start = sc.nextInt();
        System.out.print("Enter the end value: ");
        int end = sc.nextInt();
        for (int i = start; i <= end; i++) {
            if (isPrime(i)) {
                System.out.print(i + " ");
            }
        }
        sc.close();
    }
}

Sieve of Eratosthenes

import java.util.Scanner;

public class SievePrimes {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the range: ");
        int input = sc.nextInt();

        boolean[] primes = new boolean[input];

        for (int i = 0; i < primes.length; i++) {
            primes[i] = true;
        }

        for (int i = 2; i < primes.length; i++) {
            if (primes[i]) {
                for (int j = i * 2; j < primes.length; j = j + i) {
                    primes[j] = false;
                }
            }
        }

        for (int i = 0; i < primes.length; i++) {
            if (primes[i]) {
                System.out.print(i + " ");
            }
        }
    }
}

Mutiplicaton Without Using * Operator

import java.util.Scanner;

public class Multiplication {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int ans = 0;
        System.out.print("Enter first number: ");
        int a = sc.nextInt();
        System.out.print("Enter second number: ");
        int b = sc.nextInt();

        for (int i = 1; i <= b; i++) {
            ans += a;
        }

        System.out.println(a + " x " + b + " = " + ans);

        sc.close();
    }
}

Trailing Zeros

import java.util.Scanner;

public class TrailingZeros {
    public static void main(String[] args) {
        int count = 0, i = 5;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = sc.nextInt();
        while (n / i > 0) {
            count += n / i;
            i *= 5;
        }
        System.out.printf("The trailing zeros of %d! is %d", n, count);
        sc.close();
    }
}

Attendance

import java.util.Scanner;

public class Attendance {
    public static void main(String[] args) {
        int day;
        boolean attendance;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a day number: ");
        day = sc.nextInt();

        switch (day) {
            case 6:
                System.out.println("Holiday");
                attendance = false;
                break;
            case 7:
                System.out.println("Holiday");
                attendance = false;
                break;
            default:
                System.out.println("Working Day");
                attendance = true;
        }

        if (attendance) {
            System.out.println("You're makred as present");
        } else {
            System.out.println("You're makred as absent");
        }
    }
}

Simple Calculator

import java.util.Scanner;

public class Calculator {
    public static int addition(int a, int b) {
        return a + b;
    }

    public static int subtraction(int a, int b) {
        return a - b;
    }

    public static int multiplication(int a, int b) {
        return a * b;
    }

    public static int division(int a, int b) {
        return a / b;
    }

    public static void main(String[] args) {
        int num1, num2, choice;
        Scanner sc = new Scanner(System.in);

        while (true) {
            System.out.println("1. Addition");
            System.out.println("2. Subtraction");
            System.out.println("3. Multiplication");
            System.out.println("4. Division");
            System.out.println("5. Exit");
            System.out.print("Enter your choice: ");

            choice = sc.nextInt();
            if (choice == 5)
                return;
            System.out.print("Enter the first number: ");
            num1 = sc.nextInt();
            System.out.print("Enter the second number: ");
            num2 = sc.nextInt();

            switch (choice) {
                case 1:
                    System.out.println("The answer is: " + addition(num1, num2));
                    break;
                case 2:
                    System.out.println("The answer is: " + subtraction(num1, num2));
                    break;
                case 3:
                    System.out.println("The answer is: " + multiplication(num1, num2));
                    break;
                case 4:
                    System.out.println("The answer is: " + division(num1, num2));
                    break;
                default:
                    System.out.println("Invalid Input");
                    break;
            }
        }

        sc.close();
    }
}

Increasing Array

public class Increasing {
    public static boolean isIncreasing() {
        int[] arr = { 1, 2, 3, 4, 5 };

        for (int i = 0; i < arr.length - 1; i++) {
            if (arr[i] > arr[i + 1])
                return false;
        }

        return true;
    }

    public static void main(String[] args) {
        if (isIncreasing()) {
            System.out.println("The array is increasing");
        } else {
            System.out.println("The array is not increasing");
        }

    }
}

Floyd's Triangle

import java.util.Scanner;

public class FloydsTriangle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int n = sc.nextInt();

        int k = 1;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                System.out.print(k + " ");
                k++;
            }
            System.out.println();
        }

        sc.close();
    }
}

Integer To Words

public class NumberToWords999 {

    private static final String[] BELOW_20 = {
        "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine",
        "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen",
        "Sixteen", "Seventeen", "Eighteen", "Nineteen"
    };

    private static final String[] TENS = {
        "", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"
    };

    public static String numberToWords(int num) {
        if (num < 0 || num > 999) {
            return "Number out of range (0-999)";
        }
        if (num == 0) return "Zero";

        StringBuilder words = new StringBuilder();

        if (num >= 100) {
            words.append(BELOW_20[num / 100]).append(" Hundred");
            num %= 100;
            if (num != 0) words.append(" ");
        }

        if (num < 20) {
            words.append(BELOW_20[num]);
        } else {
            words.append(TENS[num / 10]);
            if (num % 10 != 0) {
                words.append(" ").append(BELOW_20[num % 10]);
            }
        }

        return words.toString().trim();
    }

    public static void main(String[] args) {
        int number = 342;
        System.out.println(numberToWords(number));  // Output: Three Hundred Forty Two
    }
}

OOPs

Class and Object

public class Car {
    String brand = "Benz";

    void honk() {
        System.out.println("Beep!");
    }

    public static void main(String[] args) {
        Car myCar = new Car();
        System.out.println(myCar.brand);
        myCar.honk();
    }
}

Inheritance

Single Inheritance

class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Barking...");
    }
}

public class SingleInhertitance {
    public static void main(String[] args) {
        // Parent Class
        System.out.println("Animal:");
        Animal animal = new Animal();
        animal.eat();

        // Child Class
        System.out.println("Dog:");
        Dog dog = new Dog();
        dog.eat();
        dog.bark();
    }
}

Multilevel Inheritance

class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Barking...");
    }
}

class Puppy extends Dog {
    void weep() {
        System.out.println("Weeping...");
    }
}

public class MultilevelInheritance {
    public static void main(String[] args) {
        // Parent Class
        Animal animal = new Animal();
        System.out.println("Animal:");
        animal.eat();

        // Child Class
        Dog dog = new Dog();
        System.out.println("Dog:");
        dog.bark();
        dog.eat();

        // Grand Child Class
        Puppy puppy = new Puppy();
        System.out.println("Puppy:");
        puppy.weep();
        puppy.bark();
        puppy.eat();
    }
}

Hierarchical Inheritance

class Animal {
    void eat() {
        System.out.println("Eating...");
    }
}

class Dog {
    void bark() {
        System.out.println("Barking...");
    }
}

class Cat {
    void meow() {
        System.out.println("Meowing...");
    }
}

public class HierarchicalInheritance {
    public static void main(String[] args) {
        // Parent class
        System.out.println("Animal:");
        Animal animal = new Animal();
        animal.eat();

        // Child Class 1
        System.out.println("Dog:");
        Dog dog = new Dog();
        dog.bark();

        // Child class 2
        System.out.println("Cat:");
        Cat cat = new Cat();
        cat.meow();
    }
}

Encpsulation

class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        if (age > 0)
            this.age = age;
        else
            System.out.println("Invalid Age");
    }
}

public class Encapsulation {
    public static void main(String[] args) {
        Person p = new Person();
        p.setName("Roopak");
        p.setAge(19);

        System.out.println("Name: " + p.getName());
        System.out.println("Age: " + p.getAge());
    }
}

Abstraction

abstract class Vehicle {
    int vehId;
    String name;

    public abstract void complyRegls();

    public abstract void capacityCheck();

    public void concreteMethod() {
        System.out.println("This is a concrete method");
    }
}

class Car extends Vehicle {

    @Override
    public void complyRegls() {
        System.out.println("Checked for comply");
    }

    @Override
    public void capacityCheck() {
        System.out.println("Checked for capacity");
    }

}

interface location {
    public void cleanLocation();

    public void hourlyMessage();
}

interface defaultUser {
    public void showIdCard();

    // default and static
    public default void hourlyMessage() {
        System.out.println("Hourly Message");
    }
}

class ServiceManager implements location, defaultUser {

    @Override
    public void showIdCard() {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'showIdCard'");
    }

    @Override
    public void cleanLocation() {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'cleanLocation'");
    }

    @Override
    public void hourlyMessage() {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'hourlyMessage'");
    }

}

public class Abstraction {
    public static void main(String[] args) {
        Car car = new Car();
        car.complyRegls();
        car.capacityCheck();

        ServiceManager sm = new ServiceManager();
        sm.hourlyMessage();
    }
}

Strings

Longest Common Prefix

import java.util.Arrays;

public class CommonSubstring {
    public static StringBuilder longestCommonPrefix(String[] strs) {
        StringBuilder sb = new StringBuilder();
        Arrays.sort(strs);
        String first = strs[0];
        String last = strs[strs.length - 1];
        for (int i = 0; i < Math.min(first.length(), last.length()); i++) {
            if (first.charAt(i) != last.charAt(i)) {
                return sb;
            }
            sb.append(first.charAt(i));
        }
        return sb;
    }

    public static void main(String[] args) {
        String[] words = { "flower", "flow", "fly" };
        System.out.println("The longest common prefix is: " + longestCommonPrefix(words));
    }
}

Bit Manipulation

Power of Two or Not

import java.util.Scanner;

public class PowerOfTwoOrNot {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        if ((num & (num - 1)) == 0) {
            System.out.println(num + " is a power of two");
        } else {
            System.out.println(num + " is not a power of two");
        }
    }
}

Extra Character in a String

public class ExtraCharactersInAString {
    public static void main(String[] args) {
        String str1 = "abce";
        String str2 = "abcde";

        char result = 0;

        String concat = str1 + str2;
        char[] chars = concat.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            result = (char) (result ^ chars[i]);
        }

        System.out.println("The extra character is: " + result);
    }
}

Recursion

Factorial

import java.util.Scanner;

public class Factorial {
    public static int factorial(int num) {
        if (num == 0 || num == 1)
            return 1;
        return num * factorial(num - 1);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        System.out.print("Factorial of " + num + " is: " + factorial(num));
        sc.close();
    }
}

Fibonacci Sequence

import java.util.Scanner;

public class Fibonacci {
    public static int fibonacci(int num) {
        if (num == 0) {
            return 0;
        } else if (num == 1) {
            return 1;
        } else {
            return fibonacci(num - 1) + fibonacci(num - 2);
        }
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = sc.nextInt();
        for (int i = 0; i < num; i++) {
            System.out.print(fibonacci(i) + " ");
        }
    }
}

Sum of n Naturals Numbers

import java.util.Scanner;

public class SumOfnNaturalNumbers {
    public static int sum(int num) {
        if (num == 1) {
            return 1;
        }
        return num + sum(num - 1);
    }

    public static void main(String[] args) {
        int num;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        num = sc.nextInt();
        System.out.println("The sum of natutals numbers till " + num + " is: " + sum(num));
    }
}

Sum of an Array

public class SumOfArray {
    public static int sum(int[] arr, int size) {
        if (size < 0) {
            return 0;
        }
        return sum(arr, size - 1) + arr[size];
    }

    public static void main(String[] args) {
        int[] arr = { 9, 7, 6, 3, 3 };
        int size = arr.length - 1;
        System.out.println("Sum of the array is: " + sum(arr, size));
    }
}

Reverse of a String

public class ReverseString {
    public static String reverse(String str, String result, int length) {
        if (length < 0) {
            return result;
        }
        result = result + str.charAt(length);
        return reverse(str, result, length - 1);
    }

    public static void main(String[] args) {
        String str = "Recursion";
        String result = "";
        int length = str.length() - 1;
        System.out.println(reverse(str, result, length));
    }
}

Euclidean Algorithm (GCD)

public class GcdOfANumber {
    public static int gcd(int a, int b) {
        if (a == 0) {
            return b;
        }
        return gcd(b % a, a);
    }

    public static void main(String[] args) {
        int a = 35, b = 15;
        System.out.printf("The GCD of %d and %d is: %d", a, b, gcd(a, b));
    }
}

Backtracking

Permutations of a String

import java.util.ArrayList;

public class PermutationsOfString {

    public static void permutation(String str, String perm, ArrayList<String> result) {
        if (str.isEmpty()) {
            result.add(perm);
        }
        for (int i = 0; i < str.length(); i++) {
            String curr = "" + str.charAt(i); // "b" in abc
            String remainingStr = str.substring(0, i) + str.substring(i + 1); // removing "b" fomr abc

            permutation(remainingStr, perm + curr, result);
        }

    }

    public static void main(String[] args) {
        String str = "ABC";
        ArrayList<String> result = new ArrayList<>();
        permutation(str, "", result);
        System.out.println("Permutations of " + str + " are: " + result);
    }

}

N Queens

public class NQueens {
    private static void placeMyQueens(int[] queens, int row) {
        if (row >= queens.length) {
            System.out.println("**********");
            for (int i = 0; i < queens.length; i++) {
                // Printing rows and columns
                System.out.println("[" + i + ", " + queens[i] + "]");
            }
        } else {

            for (int col = 0; col < queens.length; col++) {
                if (isSafe(queens, row, col)) {
                    queens[row] = col; // Placing our queen
                    placeMyQueens(queens, row + 1);
                }
            }
        }
    }

    private static boolean isSafe(int[] queens, int row, int col) {
        for (int i = 0; i < row; i++) {
            // Checking for same column
            if (queens[i] == col)
                return false;
            // Checking for top left to bottom right diagonal
            if (i - row == queens[i] - col)
                return false;
            // Checking for top right to bottom left diagonal
            if (i - row == col - queens[i])
                return false;
        }
        return true;
    }

    public static void main(String[] args) {
        int n = 4;
        // if n<4 no solution

        int[] queens = new int[n];
        int row = 0;
        placeMyQueens(queens, row);
    }
}

Restore IP Address

import java.util.ArrayList;

public class RestoreIP {
    private static boolean isValid(String current) {
        if (current.isEmpty() || current.length() > 3 || Integer.parseInt(current) > 255
                || (current.startsWith("0") && current.length() > 1)) {
            return false;
        }
        return true;
    }

    private static void restore(ArrayList<String> list, String input, String addr, int segments, int start) {
        if (segments > 3) {
            if (start == input.length())
                list.add(addr);
            return;
        }

        for (int i = start; i < input.length(); i++) {
            String current = input.substring(start, i + 1);
            if (isValid(current)) {
                if (segments == 3) {
                    restore(list, input, addr + current, segments + 1, i + 1);
                } else {
                    restore(list, input, addr + current + ".", segments + 1, i + 1);
                }
            }
        }

    }

    public static void main(String[] args) {
        String input = "25525511132", addr = "";
        int start = 0, segments = 0;
        ArrayList<String> list = new ArrayList<>();
        restore(list, input, addr, segments, start);
        System.out.println(list);
    }
}

Multi-Threading

Thread

public class MultiThread extends java.lang.Thread {
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        MultiThread multiThread1 = new MultiThread(); // className objectName = new className();
        multiThread1.start();

        MultiThread multiThread2 = new MultiThread();
        multiThread2.start();

        MultiThread multiThread3 = new MultiThread();
        multiThread3.start();
    }

}

Runnable

public class ThreadRunnable implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println(i);
        }
    }

    public static void main(String[] args) {
        ThreadRunnable threadRunnable1 = new ThreadRunnable();
        Thread thread1 = new Thread(threadRunnable1); // Passing the object of the user defined class
        thread1.start();

        ThreadRunnable threadRunnable2 = new ThreadRunnable();
        Thread thread2 = new Thread(threadRunnable2); // Passing the object of the user defined class
        thread2.start();

        ThreadRunnable threadRunnable3 = new ThreadRunnable();
        Thread thread3 = new Thread(threadRunnable3); // Passing the object of the user defined class
        thread3.start();
    }
}

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages