30 days of coding

Objective 
In this challenge, we review some basic concepts that will get you started with this series. 

Task 
To complete this challenge, you must save a line of input from stdin to a variable, print Hello, World. on a single line, and finally print the value of your variable on a second line.

You’ve got this!

Note: The instructions are Java-based, but we support submissions in many popular languages. You can switch languages using the drop-down menu above your editor, and the inputString variable may be written differently depending on the best-practice conventions of your submission language.

Input Format

A single line of text denoting inputString (the variable whose contents must be printed).

Output Format

Print Hello, World. on the first line, and the contents of inputString on the second line.

Sample Input

Welcome to 30 Days of Code!

Sample Output

Hello, World. 
Welcome to 30 Days of Code!

Solution:

public class HelloWorld {
	public static void main(String[] args) {
		// Create a Scanner object to read input from stdin.
		Scanner scan = new Scanner(System.in);

		// Read a full line of input from stdin and save it to our variable,
		// inputString.
		String inputString = scan.nextLine();

		// Close the scanner object, because we've finished reading
		// all of the input from stdin needed for this challenge.
		scan.close();

		// Print a string literal saying "Hello, World." to stdout.
		System.out.println("Hello, World.");

		System.out.println(inputString);

	}
}

Objective 
Today, we’re discussing data types.

Task 
Complete the code in the editor below. The variables iand s are already declared and initialized for you. You must:

  1. Declare 3 variables: one of type int, one of type double, and one of type String.
  2. Read 3 lines of input from stdin (according to the sequence given in the Input Format section below) and initialize your variables.
  3. Use the + operator to perform the following operations: 
    1. Print the sum of i plus your int variable on a new line.
    2. Print the sum of d plus your double variable to a scale of one decimal place on a new line.
    3. Concatenate s with the string you read as input and print the result on a new line.

Note: If you are using a language that doesn’t support using + for string concatenation (e.g.: C), you can just print one variable immediately following the other on the same line. The string provided in your editor must be printed first, immediately followed by the string you read as input.

Input Format

The first line contains an integer that you must sum with i
The second line contains a double that you must sum with d
The third line contains a string that you must concatenate with s.

Output Format

Print the sum of both integers on the first line, the sum of both doubles (scaled to 1 decimal place) on the second line, and then the two concatenated strings on the third line.

Sample Input

12
4.0
is the best place to learn and practice coding!

Sample Output

16
8.0
This is the best place to learn and practice coding!

Solution:

public class DataTypes {
	public static void main(String[] args) {
		int i = 4;
		double d = 4.0;
		String s = "This";

		Scanner scan = new Scanner(System.in);

		/* Declare second integer, double, and String variables. */
		int ii = scan.nextInt();
		scan.nextLine();
		double dd = scan.nextDouble();
		scan.nextLine();
		String ss = scan.nextLine();

		System.out.println(i + ii);
		System.out.println(d + dd);
		System.out.println(s + ss);

		/* Read and save an integer, double, and String to your variables. */
		// Note: If you have trouble reading the entire String, please go back and
		// review the Tutorial closely.

		/* Print the sum of both integer variables on a new line. */

		/* Print the sum of the double variables on a new line. */

		/*
		 * Concatenate and print the String variables on a new line; the 's' variable
		 * above should be printed first.
		 */

		scan.close();
	}
}

Objective 
In this challenge, you’ll work with arithmetic operators.

Task 
Given the meal price (base cost of a meal), tip percent (the percentage of the meal price being added as tip), and tax percent(the percentage of the meal price being added as tax) for a meal, find and print the meal’s total cost.

Note: Be sure to use precise values for your calculations, or you may end up with an incorrectly rounded result!

Input Format

There are 3 lines of numeric input: 
The first line has a double, mealCost (the cost of the meal before tax and tip). 
The second line has an integer, tipPercent (the percentage of mealCost being added as tip). 
The third line has an integer, taxPercent (the percentage of mealCost being added as tax).

Output Format

Print the total meal cost, where totalCost is the rounded integer result of the entire bill (mealCost with added tax and tip).

Sample Input

12.00
20
8

Sample Output

15

Solution:

public class Operators {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		double mealCost = scan.nextDouble(); // original meal price
		int tipPercent = scan.nextInt(); // tip percentage
		int taxPercent = scan.nextInt(); // tax percentage
		scan.close();

		// Write your calculation code here.
		double tC = mealCost + (mealCost * tipPercent) / 100 + (mealCost * taxPercent) / 100;

		// cast the result of the rounding operation to an int and save it as totalCost
		int totalCost = (int) Math.round(tC);
		System.out.println("The total meal cost is " + totalCost + " dollars.");
		// Print your result
	}
}

Objective 
In this challenge, we’re getting started with conditional statements.

Task 
Given an integer, n, perform the following conditional actions:

  • If n is odd, print Weird
  • If n is even and in the inclusive range of 2 to 5, print Not Weird
  • If n is even and in the inclusive range of 6 to 20, print Weird
  • If n is even and greater than 20, print Not Weird

Complete the stub code provided in your editor to print whether or not n is weird.

Input Format

A single line containing a positive integer, n.

Constraints

  • 1≤ n ≤ 100

Output Format

Print Weird if the number is weird; otherwise, print Not Weird.

Sample Input 0

3

Sample Output 0

Weird

Sample Input 1

24

Sample Output 1

Not Weird

Solution:

public class IntroToConditionalStatements {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int n = scan.nextInt();
		scan.close();
		String ans = "";

		// if 'n' is NOT evenly divisible by 2 (i.e.: n is odd)
		if (n % 2 == 1) {
			ans = "Weird";
		} else {
			if (n >= 6 && n <= 20) {
				System.out.println("Weird");
			} else {
				System.out.println("Not Weird");

			}
		}
		System.out.println(ans);
	}
}

Objective 
In this challenge, we’re going to learn about the difference between a class and an instance; because this is an Object Orientedconcept, it’s only enabled in certain languages.

Task 
Write a Person class with an instance variable, age, and a constructor that takes an integer, initialAge, as a parameter. The constructor must assign initialAge to age after confirming the argument passed as initialAge is not negative; if a negative argument is passed as initialAge, the constructor should set age to 0 and print Age is not valid, setting age to 0.. In addition, you must write the following instance methods:

  1. yearPasses() should increase the age  instance variable by .
  2. amIOld() should perform the following conditional actions:
    • If age < 13 print You are young..
    • If age ≥  13 and age < 18, print You are a teenager..
    • Otherwise, print You are old..

To help you learn by example and complete this challenge, much of the code is provided for you, but you’ll be writing everything in the future. The code that creates each instance of your Person class is in the main method. Don’t worry if you don’t understand it all quite yet!

Note: Do not remove or alter the stub code in the editor.

Input Format

Input is handled for you by the stub code in the editor.

The first line contains an integer, t (the number of test cases), and the t subsequent lines each contain an integer denoting the age of a Person instance.

Constraints

  • 1 ≤ T ≤ 4       
  • -5 ≤ age ≤ 30      

Output Format

Complete the method definitions provided in the editor so they meet the specifications outlined above; the code to test your work is already in the editor. If your methods are implemented correctly, each test case will print 2 or 3 lines (depending on whether or not a valid initialAge was passed to the constructor).

Sample Input

4
-1
10
16
18

Sample Output

Age is not valid, setting age to 0.
You are young.
You are young.

You are young.
You are a teenager.

You are a teenager.
You are old.

You are old.
You are old.

Solution:

class Person {
	private int age;

	public Person(int initialAge) {
		if (initialAge < 0) {
			System.out.println("Age is not valid, setting age to 0.");
		}
		this.age = initialAge;
		// Add some more code to run some checks on initialAge
	}

	public void amIOld() {
		// Write code determining if this person's age is old and print the correct
		// statement:
		if (age < 13) {
			System.out.println("You are young.");
		} else if (age >= 13 && age < 18) {
			System.out.println("You are a teenager.");

		} else {
			System.out.println("You are old.");
		}

	}

	public void yearPasses() {
		// Increment this person's age.
		this.age++;
	}
}

Objective 
In this challenge, we’re going to use loops to help us do some simple math.

Task 
Given an integer, n, print its first 10 multiples. Each multiple n x i (where 1 ≤ i ≤ 10) should be printed on a new line in the form: n x i = result.

Input Format

A single integer, n.

Constraints

  • 2 ≤ n ≤ 20      

Output Format

Print 10 lines of output; each line i (where 1 ≤ i ≤ 10) contains the result of n x i in the form: 
n x i = result.

Sample Input

2

Sample Output

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20

Solution:

public class Loops {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		in.close();
		for (int i = 1; i <= 10; i++) {
			System.out.println(n + " x " + i + " = " + n * i);
		}
	}
}

Objective 
Today we’re expanding our knowledge of Strings and combining it with what we’ve already learned about loops.

Task 
Given a string, S, of length N that is indexed from 0 to N – 1, print its even-indexed and odd-indexed characters as 2 space-separated strings on a single line (see the Sample below for more detail).

Note: 0 is considered to be an even index.

Input Format

The first line contains an integer, T (the number of test cases). 
Each line i of the T subsequent lines contain a String, S.

Constraints

  • 1 ≤ T ≤ 10       
  • 2 ≤ length of S ≤ 10000       

Output Format

For each String Sj (where 0 ≤ j ≤ T – 1 ), print Sj ‘s even-indexed characters, followed by a space, followed by Sj ‘s odd-indexed characters.

Sample Input

2
Hacker
Rank

Sample Output

Hce akr
Rn ak

Solution:

public class LetsReview {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int noOfTest = sc.nextInt();
		sc.nextLine();
		String str1 = "", str2 = "";
		for (int i = 0; i < noOfTest; i++) {
			String input = sc.next();
			char[] char1 = input.toCharArray();
			for (int j = 0; j < char1.length; j++) {
				if (j % 2 == 0) {
					str1 = str1 + char1[j];
				} else {
					str2 = str2 + char1[j];

				}
			}
			System.out.println(str1 + " " + str2);
			str1 = str2 = "";
		}
		sc.close();
	}
}

Objective 
Today, we’re learning about the Array data structure.

Task 
Given an array, A, of N integers, print A‘s elements in reverse order as a single line of space-separated numbers.

Input Format

The first line contains an integer,  N(the size of our array). 
The second line contains N space-separated integers describing array A‘s elements.

Constraints

  • 1 ≤ N ≤ 1000
  • 1 ≤ Ai ≤ 10000, where Ai is the ith integer in the array.

Output Format

Print the elements of array A in reverse order as a single line of space-separated numbers.

Sample Input

4
1 4 3 2

Sample Output

2 3 4 1

Solution:

public class Arrays {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int[] arr = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = in.nextInt();
		}
		in.close();
		for (int i = n - 1; i >= 0; i--) {

			System.out.print(arr[i] + " ");
		}
	}
}

Objective 
Today, we’re learning about Key-Value pair mappings using a Map or Dictionary data structure. 

Task 
Given n names and phone numbers, assemble a phone book that maps friends’ names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for name is not found, print Not foundinstead.

Note: Your phone book should be a Dictionary/Map/HashMap data structure.

Input Format

The first line contains an integer, n, denoting the number of entries in the phone book. 
Each of the n subsequent lines describes an entry in the form of  space-separated values on a single line. The first value is a friend’s name, and the second value is an 8-digit phone number.

After the n lines of phone book entries, there are an unknown number of lines of queries. Each line (query) contains a name to look up, and you must continue reading lines until there is no more input.

Note: Names consist of lowercase English alphabetic letters and are first names only.

Constraints

  • ≤ n ≤ 105

  • ≤ queries ≤ 105

Output Format

On a new line for each query, print Not found if the name has no corresponding entry in the phone book; otherwise, print the full name and phoneNumber in the format name=phoneNumber.

Sample Input

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

Sample Output

sam=99912222
Not found
harry=12299933

Solution:

public class DictionariesAndMaps {
	public static void main(String[] argh) {
		Scanner in = new Scanner(System.in);
		HashMap<String, Integer> hmap = new HashMap<String, Integer>();
		int n = in.nextInt();
		for (int i = 0; i < n; i++) {
			String name = in.next();
			int phone = in.nextInt();
			hmap.put(name, phone);
			// Write code here
		}
		while (in.hasNext()) {
			String s = in.next();

			if (hmap.containsKey(s)) {
				System.out.println(s + "=" + hmap.get(s));

			} else {
				System.out.println("Not found");
			}

			// Write code here
		}
		in.close();
	}
}

Objective 
Today, we’re learning and practicing an algorithmic concept called Recursion.

Recursive Method for Calculating Factorial 

KodNest factor

Task 
Write a factorial function that takes a positive integer, N as a parameter and prints the result of N! (N factorial).

Note: If you fail to use recursion or fail to name your recursive function factorial or Factorial, you will get a score of 0.

Input Format

A single integer, N (the argument to pass to factorial).

Constraints

  • 2 ≤ N ≤ 12       
  • Your submission must contain a recursive function named factorial.

Output Format

Print a single integer denoting N!.

Sample Input

3

Sample Output

6

Solution:

public class Recursion {
	public static int factorial(int i) {
		if (i == 1 || i == 0) {
			return 1;
		} else {
			return i * factorial(i - 1);
		}
	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int i = sc.nextInt();
		System.out.println(factorial(i));
		sc.close();
	}
}

Objective 
Today, we’re working with binary numbers.

Task 
Given a base-10 integer, n, convert it to binary (base-2). Then find and print the base-10 integer denoting the maximum number of consecutive 1‘s in n‘s binary representation.

Input Format

A single integer, n.

Constraints

  • ≤ n ≤ 106

Output Format

Print a single base-10 integer denoting the maximum number of consecutive 1‘s in the binary representation of n.

Sample Input 1

5

Sample Output 1

1

Sample Input 2

13

Sample Output 2

2

Solution:

public class BinaryNumbers {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		in.close();
		int r = n, counter = 0, maxOne = 0;
		String s = "";
		while (n > 0) {

			r = n % 2;
			if (r == 1) {
				counter++;
				if (counter > maxOne) {
					maxOne = counter;
				}
			} else {
				counter = 0;
			}
			s = r + s;
			n = n / 2;

		}
		System.out.println(maxOne);

	}
}

Objective 
Today, we’re building on our knowledge of Arrays by adding another dimension.

Context 
Given a 6 x 6 2D ArrayA:

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0

We define an hourglass in A to be a subset of values with indices falling in this pattern in A‘s graphical representation:

a b c
  d
e f g

There are 16 hourglasses in A, and an hourglass sum is the sum of an hourglass’ values.

Task 
Calculate the hourglass sum for every hourglass in A, then print the maximum hourglass sum.

Input Format

There are 6 lines of input, where each line contains 6 space-separated integers describing 2D Array A; every value in A will be in the inclusive range of -9 to 9.

Constraints

  • -9 ≤ A[i][j] ≤ 9       
  • 0≤ i,j ≤ 5       

Output Format

Print the largest (maximum) hourglass sum found in A.

Sample Input

1 1 1 0 0 0
0 1 0 0 0 0
1 1 1 0 0 0
0 0 2 4 4 0
0 0 0 2 0 0
0 0 1 2 4 0

Sample Output

19

Solution:

public class 2DArrays {

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int arr[][] = new int[6][6];
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 6; j++) {
				arr[i][j] = in.nextInt();
			}
		}
		in.close();
		int sum = 0, maxSum = Integer.MIN_VALUE;
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 6; j++) {
				if ((i + 2) < 6 && (j + 2) < 6) {
					sum = arr[i][j] + arr[i][j + 1] + arr[i][j + 2] + arr[i + 1][j + 1] + arr[i + 2][j]
							+ arr[i + 2][j + 1] + arr[i + 2][j + 2];
				}
				if (sum > maxSum) {
					maxSum = sum;
				}
			}

		}
		System.out.println(maxSum);
	}
}

Objective 
Today, we’re delving into Inheritance.

Task 
You are given two classes, Person and Student, where Person is the base class and Student is the derived class. Completed code for Person and a declaration for Student are provided for you in the editor. Observe that Student inherits all the properties of Person.

Complete the Student class by writing the following:

  • Student class constructor, which has 4 parameters:
    1. A string, firstName.
    2. A string, lastName.
    3. An integer, id.
    4. An integer array (or vector) of test scores, scores.
  • char calculate() method that calculates a Student object’s average and returns the grade character representative of their calculated average:

KodNest 1458142706 3073bc9143 Grading

Input Format

The locked stub code in your editor calls your Student class constructor and passes it the necessary arguments. It also calls the calculate method (which takes no arguments).

You are not responsible for reading the following input from stdin: 
The first line contains firstNamelastName and id, respectively. The second line contains the number of test scores. The third line of space-separated integers describes scores.

Constraints

  • 1 ≤ |firstName|, |lastName| ≤ 10      
  • |id| = 7
  • 0 ≤ score, average ≤ 100     

Output Format

This is handled by the locked stub code in your editor. Your output will be correct if your Student class constructor and calculate() method are properly implemented.

Sample Input

Heraldo Memelli 8135627
2
100 80

Sample Output

 Name: Memelli, Heraldo
 ID: 8135627
 Grade: O

Solution:

public class Student extends Person {
	private int[] testScores;

	Student(String firstName, String lastName, int id, int[] testScores) {
		super(firstName, lastName, id);

		this.testScores = testScores;
	}

	public char calculate() {
		int sum = 0;
		for (int i = 0; i < testScores.length; i++) {
			sum += testScores[i];
		}
		int avg = (sum) / testScores.length;

		if (90 <= avg && avg <= 100) {
			return 'O';
		} else if (80 <= avg && avg < 90) {
			return 'E';
		} else if (70 <= avg && avg < 80) {
			return 'A';
		} else if (55 <= avg && avg < 70) {
			return 'P';
		} else if (40 <= avg && avg < 55) {
			return 'D';
		} else {
			return 'T';
		}

	}

}

Objective 
Today, we’re taking what we learned yesterday about Inheritance and extending it to Abstract Classes. Because this is a very specific Object-Oriented concept, submissions are limited to the few languages that use this construct.

Task 
Given a Book class and a Solution class, write a MyBook class that does the following:

  • Inherits from Book
  • Has a parameterized constructor taking these 3 parameters:
    1. string title
    2. string author
    3. int price
  • Implements the Book class’ abstract display() method so it prints these 3 lines:
    1. , a space, and then the current instance’s title.
    2. , a space, and then the current instance’s author.
    3. , a space, and then the current instance’s price.

Note: Because these classes are being written in the same file, you must not use an access modifier (e.g.: public) when declaring MyBook or your code will not execute.

Input Format

You are not responsible for reading any input from stdin. The Solution class creates a Book object and calls the MyBook class constructor (passing it the necessary arguments). It then calls the display method on the Book object.

Output Format

The void display() method should print and label the respective titleauthor, and price of the MyBook object’s instance (with each value on its own line) like so:

Title: $title
Author: $author
Price: $price

Note: The $ is prepended to variable names to indicate they are placeholders for variables.

Sample Input

The following input from stdin is handled by the locked stub code in your editor:

The Alchemist
Paulo Coelho
248

Sample Output

The following output is printed by your display() method:

Title: The Alchemist
Author: Paulo Coelho
Price: 248

Solution:

class MyBook extends Book{
    private int price;
    MyBook(String $title,String $author,int $price){
        super($title,$author);
        this.price=$price;
    }
 
    void display(){
        System.out.println("Title: "+title);
        System.out.println("Author: "+author);
        System.out.println("Price: "+price);

    }
}
class Book{
 String title;
 String author;
	/**
	 * @param $title
	 * @param $author
	 */
	public Book(String $title, String $author) {
		this.author=$author;
		this.title=$title;
	}
	
}

Objective 
Today we’re discussing scope.


The absolute difference between two integers, a and b, is written as |a – b|. The maximum absolute difference between two integers in a set of positive integers,elements , is the largest absolute difference between any two integers in elements .

The Difference class is started for you in the editor. It has a private integer array (elements ) for storing N non-negative integers, and a public integer (maximumDifference) for storing the maximum absolute difference.

Task 
Complete the Difference class by writing the following:

  • A class constructor that takes an array of integers as a parameter and saves it to the elements  instance variable.
  • computeDifference method that finds the maximum absolute difference between any 2 numbers in N and stores it in the maximumDifference instance variable.

Input Format

You are not responsible for reading any input from stdin. The locked Solution class in your editor reads in 2 lines of input; the first line contains N, and the second line describes the elements  array.

Constraints

  • 1 ≤ N ≤ 10       
  • 1 ≤ elements[i] ≤ 100 , where 0 ≤ i ≤ N – 1       

Output Format

You are not responsible for printing any output; the Solution class will print the value of the maximumDifference instance variable.

Sample Input

3
1 2 5

Sample Output

4

Solution:

public class Scope {

	/**
	 * 
	 * @param elements
	 
Difference(int [] elements){
    this.elements=elements;
}
    
 void computeDifference() {
		int maxNum = elements[0];
		int minNum = maxNum;
		for (int i = 1; i < elements.length; i++) {
			
			maxNum=elements[i]>maxNum?elements[i]:maxNum;
			minNum=elements[i]>minNum?minNum:elements[i];
			
		}
		maximumDifference=Math.abs(maxNum-minNum);
	}
	*/
}

Objective 
Today we’re working with Linked Lists.


Node class is provided for you in the editor. A Node object has an integer data field, data, and a Node instance pointer, next, pointing to another node (i.e.: the next node in a list).

Node insert function is also declared in your editor. It has two parameters: a pointer, head, pointing to the first node of a linked list, and an integer data value that must be added to the end of the list as a new Node object.

Task 
Complete the insert function in your editor so that it creates a new Node (pass data as the Node constructor argument) and inserts it at the tail of the linked list referenced by the head parameter. Once the new node is added, return the reference to the head node.

Note: If the head argument passed to the insert function is null, then the initial list is empty.

Input Format

The insert function has 2 parameters: a pointer to a Node named head, and an integer value, data
The constructor for Node has 1 parameter: an integer value for the data field.

You do not need to read anything from stdin.

Output Format

Your insert function should return a reference to the head node of the linked list.

Sample Input

The following input is handled for you by the locked code in the editor: 
The first line contains T, the number of test cases. 
The  subsequent lines of test cases each contain an integer to be inserted at the list’s tail.

4
2
3
4
1

Sample Output

2 3 4 1

Solution:

public class LinkedList {
	static class Node{
		int data;
		Node next;
		Node(int data){
			this.data=data;
		}
	}
	 public static  Node insert(Node head,int data) {
	        //Complete this method
	        Node newNode=new Node(data);
	        if(head==null) return newNode;
	       Node node=head;
	        while(node.next!=null){
	            node=node.next;
	        }
	        node.next=newNode;
	        return head;

	    }

}

Objective 
Today, we’re getting started with Exceptions by learning how to parse an integer from a string and print a custom error message.

Task 
Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String.

Note: You must use the String-to-Integer and exception handling constructs built into your submission language. If you attempt to use loops/conditional statements, you will get a 0 score.

Input Format

A single string, S.

Constraints

  • 1 ≤ |S| ≤ 6, where |S| is the length of string S.
  • S is composed of either lowercase letters (a – zor decimal digits (0 – 9).

Output Format

Print the parsed integer value of S, or Bad String if S cannot be converted to an integer.

Sample Input 0

3

Sample Output 0

3

Sample Input 1

za

Sample Output 1

Bad String

Solution:

public class ExceptionsStringToInteger {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		String S = in.next();
		in.close();
		int i = 0;
		try {
			i = Integer.parseInt(S);
			System.out.println(i);

		} catch (NumberFormatException e) {
			System.out.println("Bad String");
		}
	}
}

Objective 
Yesterday’s challenge taught you to manage exceptional situations by using try and catch blocks. In today’s challenge, you’re going to practice throwing and propagating an exception.

Task 
Write a Calculator class with a single method: int power(int,int). The power method takes two integers, n and p, as parameters and returns the integer result of np. If either n or p is negative, then the method must throw an exception with the message: n and p should be non-negative.

Note: Do not use an access modifier (e.g.: public) in the declaration for your Calculator class.

Input Format

Input from stdin is handled for you by the locked stub code in your editor. The first line contains an integer, T, the number of test cases. Each of the T subsequent lines describes a test case in 2 space-separated integers denoting n and p, respectively.

Constraints

  • No Test Case will result in overflow for correctly written code.

Output Format

Output to stdout is handled for you by the locked stub code in your editor. There are T lines of output, where each line contains the result of np as calculated by your Calculator class’ power method.

Sample Input

4
3 5
2 4
-1 -2
-1 3

Sample Output

243
16
n and p should be non-negative
n and p should be non-negative

Solution:

public class MoreExceptions {
	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);
		int t = in.nextInt();
		while (t-- > 0) {

			int n = in.nextInt();
			int p = in.nextInt();
			Calculator myCalculator = new Calculator();
			try {
				int ans = myCalculator.power(n, p);
				System.out.println(ans);
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
		in.close();
	}
}

Welcome to Day 18! Today we’re learning about Stacks and Queues.

palindrome is a word, phrase, number, or other sequence of characters which reads the same backwards and forwards. Can you determine if a given string, s, is a palindrome?

To solve this challenge, we must first take each character in senqueue it in a queue, and also push that same character onto a stack. Once that’s done, we must dequeue the first character from the queue and pop the top character off the stack, then compare the two characters to see if they are the same; as long as the characters match, we continue dequeueing, popping, and comparing each character until our containers are empty (a non-match means s isn’t a palindrome).

Write the following declarations and implementations:

  1. Two instance variables: one for your stack, and one for your queue.
  2. void pushCharacter(char ch) method that pushes a character onto a stack.
  3. void enqueueCharacter(char ch) method that enqueues a character in the queue instance variable.
  4. char popCharacter() method that pops and returns the character at the top of the stack instance variable.
  5. char dequeueCharacter() method that dequeues and returns the first character in the queue instance variable.

Input Format

You do not need to read anything from stdin. The locked stub code in your editor reads a single line containing string s. It then calls the methods specified above to pass each character to your instance variables.

Constraints

  • s is composed of lowercase English letters.

Output Format

You are not responsible for printing any output to stdout. 
If your code is correctly written and s is a palindrome, the locked stub code will print The word, s, is a palindrome.; otherwise, it will print The word, s, is not a palindrome.

Sample Input

racecar

Sample Output

The word, racecar, is a palindrome.

Solution:

public class QueuesAndStacks {
	Stack st = new Stack();
	Queue q = new LinkedList();

	void pushCharacter(char ch) {
		st.push(ch);
	}

	void enqueueCharacter(char ch) {
		q.add(ch);
	}

	char popCharacter() {
		return st.pop();
	}

	char dequeueCharacter() {
		return q.poll();
	}
}

Objective 
Today, we’re learning about Interfaces.

Task 
The AdvancedArithmetic interface and the method declaration for the abstract divisorSum(n) method are provided for you in the editor below.

Complete the implementation of Calculator class, which implements the AdvancedArithmetic interface. The implementation for the divisorSum(n) method must return the sum of all divisors of n.

Input Format

A single line containing an integer, n.

Constraints

  • 1 ≤ n ≤ 1000

Output Format

You are not responsible for printing anything to stdout. The locked template code in the editor below will call your code and print the necessary output.

Sample Input

6

Sample Output

I implemented: AdvancedArithmetic
12

Solution:

interface AdvancedArithmetic{
	   int divisorSum(int n);
	}
//renamed Calculator class to Calculator2 class as its already present in Day18 question
class Calculator2 implements AdvancedArithmetic{
    
    public int divisorSum(int n){
        if(n==1)return 1;
       int sum=1+n,r=0;
        for(int i=2;i<n;i++){
         
            r=n%i;
            if(r==0){
                sum=sum+i;
            }
        }
        return sum;
    }
    
}
public class Interfaces {
	 public static void main(String[] args) {
	        Scanner scan = new Scanner(System.in);
	        int n = scan.nextInt();
	        scan.close();
	        
	      	AdvancedArithmetic myCalculator = new Calculator2(); 
	        int sum = myCalculator.divisorSum(n);
	        System.out.println("I implemented: " + myCalculator.getClass().getInterfaces()[0].getName() );
	        System.out.println(sum);
	    }
	}

Objective 
Today, we’re discussing a simple sorting algorithm called Bubble Sort.


Consider the following version of Bubble Sort:

for (int i = 0; i < n; i++) {
    // Track number of elements swapped during a single array traversal
    int numberOfSwaps = 0;
    
    for (int j = 0; j < n - 1; j++) {
        // Swap adjacent elements if they are in decreasing order
        if (a[j] > a[j + 1]) {
            swap(a[j], a[j + 1]);
            numberOfSwaps++;
        }
    }
    
    // If no elements were swapped during a traversal, array is sorted
    if (numberOfSwaps == 0) {
        break;
    }
}

Task 
Given an array, a, of size n distinct elements, sort the array in ascending order using the Bubble Sort algorithm above. Once sorted, print the following 3 lines:

  1. Array is sorted in numSwaps swaps. 
    where numSwaps is the number of swaps that took place.
  2. First Element: firstElement 
    where firstElement is the first element in the sorted array.
  3. Last Element: lastElement 
    where lastElement is the last element in the sorted array.

Hint: To complete this challenge, you will need to add a variable that keeps a running tally of all swaps that occur during execution.

Input Format

The first line contains an integer, n, denoting the number of elements in array a
The second line contains n space-separated integers describing the respective values of a0,a1,…,an-1.

Constraints

  • 2 ≤ n ≤ 600      
  • ≤ a≤ 2 x 106, where 0 ≤ i ≤ n.

Output Format

Print the following three lines of output:

  1. Array is sorted in numSwaps swaps. 
    where numSwaps is the number of swaps that took place.
  2. First Element: firstElement 
    where firstElement is the first element in the sorted array.
  3. Last Element: lastElement 
    where lastElement is the last element in the sorted array.

Sample Input 0

3
1 2 3

Sample Output 0

Array is sorted in 0 swaps.
First Element: 1
Last Element: 3

Solution:

public class Sorting {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int a[] = new int[n];
		for (int a_i = 0; a_i < n; a_i++) {
			a[a_i] = in.nextInt();
		}
		in.close();
		int count = 0;
		boolean swapped = true;
		for (int j = a.length - 1; (j >= 0 && swapped); j--) {
			swapped = false;
			for (int k = 0; k < j; k++) {

				if (a[k] > a[k + 1]) {
					int temp = a[k];
					count++;
					a[k] = a[k + 1];
					a[k + 1] = temp;
					swapped = true;
				}
			}
		}
		System.out.println("Array is sorted in " + count + " swaps.");
		System.out.println("First Element: " + a[0]);
		System.out.println("Last Element: " + a[a.length - 1]);

	}
}

Objective 
Today we’re discussing Generics; be aware that not all languages support this construct, so fewer languages are enabled for this challenge.

Task 
Write a single generic function named printArray; this function must take an array of generic elements as a parameter (the exception to this is C++, which takes a vector). The locked Solution class in your editor tests your function.

Note: You must use generics to solve this challenge. Do not write overloaded functions.

Input Format

The locked Solution class in your editor will pass different types of arrays to your printArray function.

Constraints

  • You must have exactly 1 function named printArray.

Output Format

Your printArray function should print each element of its generic array parameter on a new line.

Solution:

class Printer {
	void printArray(T[] inputArray) {

		for (T t : inputArray) {

			System.out.println(t);
		}
	}
}

public class Generics {

	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		Integer[] intArray = new Integer[n];
		for (int i = 0; i < n; i++) {
			intArray[i] = sc.nextInt();
		}

		n = sc.nextInt();
		String[] stringArray = new String[n];
		for (int i = 0; i < n; i++) {
			stringArray[i] = sc.next();
		}

		Printer intPrinter = new Printer();
		Printer stringPrinter = new Printer();
		intPrinter.printArray(intArray);
		stringPrinter.printArray(stringArray);
		if (Printer.class.getDeclaredMethods().length > 1) {
			System.out.println("The Printer class should only have 1 method named printArray.");
		}
		sc.close();
	}
}

Objective 
Today, we’re working with Binary Search Trees (BSTs).

Task 
The height of a binary search tree is the number of edges between the tree’s root and its furthest leaf. You are given a pointer, root, pointing to the root of a binary search tree. Complete the getHeight function provided in your editor so that it returns the height of the binary search tree.

Input Format

The locked stub code in your editor reads the following inputs and assembles them into a binary search tree: 
The first line contains an integer, n, denoting the number of nodes in the tree. 
Each of the n subsequent lines contains an integer, data, denoting the value of an element that must be added to the BST.

Output Format

The locked stub code in your editor will print the integer returned by your getHeight function denoting the height of the BST.

Sample Input

7
3
5
2
1
4
6
7

Sample Output

3

Solution:

public class BinarySearchTrees {
	static class Node {
		Node left, right;
		int data;
		Node(int data) {
			this.data = data;
			left = right = null;
		}
	}

	public static int getHeight(Node root) {
		return (root == null) ? -1 : Math.max(getHeight(root.left) + 1, getHeight(root.right) + 1);
	}

	public static Node insert(Node root, int data) {
		if (root == null) {
			return new Node(data);
		} else {
			Node cur;
			if (data <= root.data) {
				cur = insert(root.left, data);
				root.left = cur;
			} else {
				cur = insert(root.right, data);
				root.right = cur;
			}
			return root;
		}
	}

	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		Node root = null;
		while (T-- > 0) {
			int data = sc.nextInt();
			root = insert(root, data);
		}
		sc.close();
		int height = getHeight(root);
		System.out.println(height);
	}
}

Objective 
Today, we’re going further with Binary Search Trees.

Task 
A level-order traversal, also known as a breadth-first search, visits each level of a tree’s nodes from left to right, top to bottom. You are given a pointer, root, pointing to the root of a binary search tree. Complete the levelOrder function provided in your editor so that it prints the level-order traversal of the binary search tree.

Hint: You’ll find a queue helpful in completing this challenge.

Input Format

The locked stub code in your editor reads the following inputs and assembles them into a BST: 
The first line contains an integer,T  (the number of test cases). 
The T subsequent lines each contain an integer, data, denoting the value of an element that must be added to the BST.

Output Format

Print the data value of each node in the tree’s level-order traversal as a single line of N space-separated integers.

Sample Input

6
3
5
4
7
2
1

Sample Output

3 2 5 1 4 7 

Solution:

public class BSTLevelOrderTraversal {
	static class Node {
		Node left, right;
		int data;

		Node(int data) {
			this.data = data;
			left = right = null;
		}
	}

	static void levelOrder(Node root) {
		if (root == null)
			System.out.println("nothing to display");
		Queue q = new LinkedList();
		q.add(root);
		while (!q.isEmpty()) {
			Node node = (Node) q.poll();
			System.out.print(node.data + " ");
			if (node.left != null)
				q.add(node.left);
			if (node.right != null)
				q.add(node.right);

		}
	}

	public static Node insert(Node root, int data) {
		if (root == null) {
			return new Node(data);
		} else {
			Node cur;
			if (data <= root.data) {
				cur = insert(root.left, data);
				root.left = cur;
			} else {
				cur = insert(root.right, data);
				root.right = cur;
			}
			return root;
		}
	}

	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		int T = sc.nextInt();
		Node root = null;
		while (T-- > 0) {
			int data = sc.nextInt();
			root = insert(root, data);
		}
		sc.close();
		levelOrder(root);
	}
}

Task 
Node class is provided for you in the editor. A Node object has an integer data field, data, and a Node instance pointer, next, pointing to another node (i.e.: the next node in a list).

removeDuplicates function is declared in your editor, which takes a pointer to the head node of a linked list as a parameter. Complete removeDuplicates so that it deletes any duplicate nodes from the list and returns the head of the updated list.

Note: The head pointer may be null, indicating that the list is empty. Be sure to reset your next pointer when performing deletions to avoid breaking the list.

Input Format

You do not need to read any input from stdin. The following input is handled by the locked stub code and passed to the removeDuplicates function: 
The first line contains an integer, N, the number of nodes to be inserted. 
The N subsequent lines each contain an integer describing the data value of a node being inserted at the list’s tail.

Constraints

  • The data elements of the linked list argument will always be in non-decreasing order.

Output Format

Your removeDuplicates function should return the head of the updated linked list. The locked stub code in your editor will print the returned list to stdout.

Sample Input

6
1
2
2
3
3
4

Sample Output

1 2 3 4

Solution:

public class MoreLinkedLists {
	static class Node {
		int data;
		Node next;

		Node(int d) {
			data = d;
			next = null;
		}

	}

	public static Node removeDuplicates(Node head) {
		if (head == null)
			return head;
		Set s = new HashSet();
		Node node = head;
		s.add(node.data);
		Node newNode = new Node(node.data);
		node = node.next;
		Node newHead = newNode;
		while (node != null) {
			if (!s.contains(node.data)) {
				s.add(node.data);
				newNode.next = new Node(node.data);
				newNode = newNode.next;
			}
			node = node.next;
		}
		return newHead;

	}

	public static Node insert(Node head, int data) {
		Node p = new Node(data);
		if (head == null)
			head = p;
		else if (head.next == null)
			head.next = p;
		else {
			Node start = head;
			while (start.next != null)
				start = start.next;
			start.next = p;

		}
		return head;
	}

	public static void display(Node head) {
		Node start = head;
		while (start != null) {
			System.out.print(start.data + " ");
			start = start.next;
		}
	}

	public static void main(String args[]) {
		Scanner sc = new Scanner(System.in);
		Node head = null;
		int T = sc.nextInt();
		while (T-- > 0) {
			int ele = sc.nextInt();
			head = insert(head, ele);
		}
		head = removeDuplicates(head);
		display(head);
		sc.close();
	}
}

Objective 
Today we’re learning about running time!

Task 
prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Given a number, n, determine and print whether it’s Prime or Not prime.

Note: If possible, try to come up with a O(√n) primality algorithm, or see what sort of optimizations you come up with for an O(n) algorithm. Be sure to check out the Editorial after submitting your code!

Input Format

The first line contains an integer, T, the number of test cases. 
Each of the T subsequent lines contains an integer, n, to be tested for primality.

Constraints

  • 1 ≤ T ≤ 30

  • ≤ n ≤ 2 x 109

Output Format

For each test case, print whether n is Prime or Not prime on a new line.

Sample Input

3
12
5
7

Sample Output

Not prime
Prime
Prime

Solution:

public class RunningTimeAndComplexity {
	static boolean isPrime(int n) {
		if (n < 2) {
			return false;
		}
		for (int i = 2; i <= Math.sqrt(n); i++) {
			if (n % i == 0) {
				return false;
			}
		}
		return true;

	}

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		for (int i = 0; i < n; i++) {
			String result = isPrime(sc.nextInt()) ? "Prime" : "Not prime";
			System.out.println(result);
		}
		sc.close();
	}
}

Objective 
Today’s challenge puts your understanding of nested conditional statements to the test. You already have the knowledge to complete this challenge

Task 
Your local library needs your help! Given the expected and actual return dates for a library book, create a program that calculates the fine (if any). The fee structure is as follows:

  1. If the book is returned on or before the expected return date, no fine will be charged (i.e.: fine = 0).
  2. If the book is returned after the expected return day but still within the same calendar month and year as the expected return date, fine = 15 Hackos x (the number of days late).
  3. If the book is returned after the expected return month but still within the same calendar year as the expected return date, the fine = 500 Hackos x (the number of months late)
  4. If the book is returned after the calendar year in which it was expected, there is a fixed fine of 10000 Hackos.

Input Format

The first line contains 3 space-separated integers denoting the respective daymonth, and year on which the book was actually returned. 
The second line contains 3 space-separated integers denoting the respective daymonth, and year on which the book was expected to be returned (due date).

Constraints

  • 1≤ D ≤ 31

  • 1≤ M ≤ 12

  • 1≤ Y ≤ 3000

  • It is guaranteed that the dates will be valid Georgian calendar date.

Output Format

Print a single integer denoting the library fine for the book received as input.

Sample Input

9 6 2015
6 6 2015

Sample Output

45

Solution:

public class NestedLogic {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String actualDate = sc.nextLine();
		String expectedDate = sc.nextLine();
		sc.close();
		int fine = 0;
		String[] dateDetail = actualDate.split(" ");
		String[] eDetail = expectedDate.split(" ");

		int aDate = Integer.parseInt(dateDetail[0]);
		int aMonth = Integer.parseInt(dateDetail[1]);
		int ayear = Integer.parseInt(dateDetail[2]);

		int eDate = Integer.parseInt(eDetail[0]);
		int eMonth = Integer.parseInt(eDetail[1]);
		int eYear = Integer.parseInt(eDetail[2]);

		if (ayear > eYear) {
			fine = 10000;
		} else if (ayear == eYear && aMonth > eMonth) {
			fine = 500 * (aMonth - eMonth);
		} else if (ayear == eYear && aMonth == eMonth && aDate > eDate) {
			fine = 15 * (aDate - eDate);
		}
		System.out.println(fine);
	}

}

This problem is all about unit testing.

Your company needs a function that meets the following requirements:

  • For a given array of n integers, the function returns the index of the element with the minimum value in the array. If there is more than one element with the minimum value, the returned index should be the smallest one.
  • If an empty array is passed to the function, it should raise an Exception.

Note: The arrays are indexed from 0.

A colleague has written that function, and your task is to design 3 separated unit tests, testing if the function behaves correctly. The implementation in Python is listed below (Implementations in other languages can be found in the code template):

def minimum_index(seq):
    if len(seq) == 0:
        raise ValueError("Cannot get the minimum value index from an empty sequence")
    min_idx = 0
    for i in range(1, len(seq)):
        if a[i] < a[min_idx]:
            min_idx = i
    return min_idx

Another co-worker has prepared functions that will perform the testing and validate returned results with expectations. Your task is to implement 3 classes that will produce test data and the expected results for the testing functions. More specifically: function get_array() in TestDataEmptyArray class and functions get_array() and get_expected_result() in classes TestDataUniqueValues and TestDataExactlyTwoDifferentMinimums following the below specifications:

  • get_array() method in class TestDataEmptyArray has to return an empty array.
  • get_array() method in class TestDataUniqueValues has to return an array of size at least 2 with all unique elements, while method get_expected_result() of this class has to return the expected minimum value index for this array.
  • get_array() method in class TestDataExactlyTwoDifferentMinimums has to return an array where there are exactly two different minimum values, while method get_expected_result() of this class has to return the expected minimum value index for this array.

Take a look at the code template to see the exact implementation of functions that your colleagues already implemented.

Solution:

public class Testing {
	public static void main(String[] args) {
		System.out.println(5);
	    System.out.println("4 3");
	    System.out.println("0 -3 4 2");
	    System.out.println("5 2");
	    System.out.println("0 -3 4 2 2");
	    System.out.println("3 3");
	    System.out.println("0 -3 4");
	    System.out.println("7 2");
	    System.out.println("0 -3 1 1 1 1 1");
	    System.out.println("6 3");
	    System.out.println("0 -3 4 2 1 1");
	    /**
	     * uncomment below method if you want to generate automated Testcase.
	     * Its generating proper test case and you can pass it to Angry professer program
	     * which will give you proper output. But hackerrank platform is validating based on hardcode test case, so commented
	     * the below logic. feel free to uncomment & see its working.
	     */
//		testCaseGeneration();
	    }

	/**
	 * optional , written for learning purpose
	 */
	private static void testCaseGeneration() {
		String []lectures={"YES","NO","YES","NO","YES"};
		int t = 5,m=0;
		System.out.println(t);
		while (t-- > 0) {
			String classCancel = lectures[m++];
			Random gen = new Random();
			int n = gen.nextInt(197) + 3;
			int k = gen.nextInt(n - 1) + 1;
			System.out.println(n + " " + k);
			if (classCancel.equalsIgnoreCase("YES")) {
				generateTcForFailure(n, k, gen);
			} else {
				generateTcForSuccess(n, k, gen);
			}
			System.out.println();
		}
	}

	/**
	 * @param n
	 * @param k
	 * @param gen
	 */
	private static void generateTcForFailure(int n, int k, Random random) {
		int studentCount = 0;
		String tc="";
		while (n > 0) {
			int a = random.nextInt(2000) - 1000;
			if (a < k && studentCount < k-1) {
				tc+=a+" ";
				studentCount++;
				n--;
			} else if (a > k) {
				tc+=a+" ";
				n--;
			}
		}
		System.out.print(tc.trim());
	}

	/**
	 * @param n
	 * @param k
	 */
	private static void generateTcForSuccess(int n, int k, Random random) {
		int studentCount = 0;
		String tc="";
		while (n > 0) {
			int a = random.nextInt(2000) - 1000;
			if ( studentCount >= k) {
				tc+=a+" ";
				n--;
			} else if (a<=k  && studentCount < k) {
				studentCount++;
				tc+=a+" ";
				n--;
			}
		}
		System.out.print(tc.trim());
	}

}

Objective 
Today, we’re working with regular expressions. 

Task 
Consider a database table, Emails, which has the attributes First Name and Email ID. Given N rows of data simulating the Emails table, print an alphabetically-ordered list of people whose email address ends in @gmail.com.

Input Format

The first line contains an integer,N  , total number of rows in the table. 
Each of the N  subsequent lines contains 2 space-separated strings denoting a person’s first name and email ID, respectively.

Constraints

  • 2 ≤ N ≤ 30
  • Each of the first names consists of lower case letters [a – z] only.
  • Each of the email IDs consists of lower case letters [a – z]@ and . only.
  • The length of the first name is no longer than 20.
  • The length of the email ID is no longer than 50.

Output Format

Print an alphabetically-ordered list of first names for every user with a gmail account. Each name must be printed on a new line.

Sample Output

julia
julia
riya
samantha
tanya

Solution:

public class RegExPatternsAndIntroToDatabases {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int N = in.nextInt();
		List list = new ArrayList();
		for (int a0 = 0; a0 < N; a0++) {
			String firstName = in.next();
			String emailID = in.next();
			String regExPattern = "[a-z][email protected]";

			Pattern p = Pattern.compile(regExPattern);
			Matcher m = p.matcher(emailID);
			if (m.find()) {
				list.add(firstName);
			}

		}
		Collections.sort(list);
		for (String string : list) {
			System.out.println(string);
		}
		in.close();
	}
}

Objective 
Welcome to the last day! Today, we’re discussing bitwise operations.

Task 
Given set S = {1,2,3,…,N}. Find two integers, A and B (where A < B), from set S such that the value of A&B is the maximum possible and also less than a given integer, K. In this case, & represents the bitwise AND operator.

Input Format

The first line contains an integer, T, the number of test cases. 
Each of the T subsequent lines defines a test case as 2 space-separated integers, N and K, respectively.

Constraints

  • ≤ T ≤ 103

  • 2 ≤ N ≤ 103

  • 2 ≤ K ≤ N

Output Format

For each test case, print the maximum possible value of A&B on a new line.

Sample Input

3
5 2
8 5
2 2

Sample Output

1
4
0

Solution:

public class BitwiseAND {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int t = in.nextInt();
		for (int a0 = 0; a0 < t; a0++) {
			int n = in.nextInt();
			int k = in.nextInt();
			in.close();
			if (((k - 1) | k) <= n) {
				System.out.println(k - 1);
			} else {
				System.out.println(k - 2);
			}

		}
	}
}

Related Articles

Core Java

1. What are primitive types in Java ? byte, short, int, long, float, double, char, boolean… 2. What are tokens? Name the 5 types of tokens available in Java with an example…

JavaScript

Explain event delegation Event delegation is a technique involving adding event listeners to a parent element instead of adding them to the descendant elements. The…

CSS

What is CSS selector specificity and how does it work? The browser determines what styles to show on an element depending on the specificity of…

CSS

1. What is CSS ? CSS is the language for describing the presentation of Web pages, including colors, layout, and fonts. It allows one to…

Responses

Your email address will not be published. Required fields are marked *

×