0% found this document useful (0 votes)
16 views3 pages

Odd Numbers Counter in Java

The document outlines five Java programming problems along with their descriptions, input/output formats, sample inputs/outputs, and Java solutions. The problems include counting odd/even numbers, calculating factorials, checking for palindromes, finding the maximum number in an array, and summing the digits of an integer. Each problem is presented with a clear structure for implementation in Java.

Uploaded by

venkypotla19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views3 pages

Odd Numbers Counter in Java

The document outlines five Java programming problems along with their descriptions, input/output formats, sample inputs/outputs, and Java solutions. The problems include counting odd/even numbers, calculating factorials, checking for palindromes, finding the maximum number in an array, and summing the digits of an integer. Each problem is presented with a clear structure for implementation in Java.

Uploaded by

venkypotla19
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

HackerRank Java Problems and Solutions

■Problem 1: Odd or Even Counter


Problem Description:
Write a program that reads a list of integers and counts how many are even and how many are odd.
Input Format:
The first line contains an integer `n` (1 <= n <= 1000) - the number of integers.
The second line contains `n` space-separated integers.
Output Format:
Two integers separated by space: the count of even numbers and the count of odd numbers.
Sample Input:
5
12345
Sample Output:
23
Java Solution:
import [Link].*;

public class OddEvenCounter {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int n = [Link]();
int even = 0, odd = 0;

for (int i = 0; i < n; i++) {


int num = [Link]();
if (num % 2 == 0)
even++;
else
odd++;
}

[Link](even + " " + odd);


}
}
------------------------------------------------------------

■Problem 2: Factorial Finder


Problem Description:
Given a non-negative integer `n`, compute its factorial.
Input Format:
A single integer `n` (0 <= n <= 20)
Output Format:
A single integer, the factorial of `n`.
Sample Input:
5
Sample Output:
120
Java Solution:
import [Link].*;

public class FactorialFinder {


public static long factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
int n = [Link]();
■Problem 3: Palindrome Checker
Problem Description:
Check if the given string is a palindrome. Ignore case and spaces.
Input Format:
A single line string.
Output Format:
Print `YES` if it is a palindrome, otherwise print `NO`.
Sample Input:
Race car
Sample Output:
YES
Java Solution:
import [Link].*;

public class PalindromeChecker {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
String s = [Link]().replaceAll("\\s", "").toLowerCase();

String reversed = new StringBuilder(s).reverse().toString();


if ([Link](reversed))
[Link]("YES");
else
[Link]("NO");
}
}
------------------------------------------------------------

■Problem 4: Maximum Number in Array


Problem Description:
Find the maximum number in an array.
Input Format:
First line contains an integer `n` (1 <= n <= 1000).
Second line contains `n` space-separated integers.
Output Format:
A single integer: the maximum value in the array.
Sample Input:
4
-1 20 3 5
Sample Output:
20
Java Solution:
import [Link].*;

public class MaxInArray {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int n = [Link]();
int max = Integer.MIN_VALUE;

for (int i = 0; i < n; i++) {


int num = [Link]();
if (num > max) max = num;
}

[Link](max);
}
}
------------------------------------------------------------
■Problem 5: Sum of Digits
Problem Description:
Given an integer, return the sum of its digits.
Input Format:
A single integer `n` (-10^6 <= n <= 10^6)
Output Format:
A single integer: the sum of digits.
Sample Input:
1234
Sample Output:
10
Java Solution:
import [Link].*;

public class SumOfDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
int n = [Link]([Link]());
int sum = 0;

while (n > 0) {
sum += n % 10;
n /= 10;
}

[Link](sum);
}
}
------------------------------------------------------------

Common questions

Powered by AI

An enhancement to the palindrome checker could involve a two-pointer technique. Instead of reversing the string and comparing, use two indices to compare characters from the beginning and end simultaneously moving towards the center . This avoids creating a new string in memory and reduces the number of operations by half, offering performance improvements on long strings due to reduced iterative operations and diminished memory consumption.

The edge cases for the palindrome checker include empty strings, single-character strings, and strings with spaces and mixed case letters. The solution handles these by removing spaces with replaceAll and converting all characters to lowercase before checking for palindrome properties . This ensures that variations in input do not affect the outcome, maintaining robustness across diverse test cases.

Converting recursive algorithms to iterative ones is often beneficial for space complexity because it avoids the stack overhead associated with recursive calls . In the factorial calculation, recursion involves stack space proportional to the depth of the recursion (O(n)), but an iterative approach uses constant space (O(1)). Given the factorial problem constraints (0 <= n <= 20), the stack usage is minimal, but iterating ensures robustness beyond these constraints in more general-use scenarios.

Space optimization in the `OddEvenCounter` algorithm is largely already accomplished, as it uses a constant amount of space regardless of input size . In contrast, potential time reduction techniques, such as concurrent processing of input data, could provide marginal gains but at the cost of added complexity and possible overhead in context switching or thread management. In practical scenarios, ensuring constant space use while maintaining clarity of the code is preferred over marginal time savings that introduce complexity.

The typical solutions provided tend to assume valid input according to specification, but real-world usage might introduce invalid inputs such as non-integer characters or numbers outside the intended range . Lack of input validation can lead to runtime exceptions or logically incorrect results. Robust solutions should incorporate input validation routines that confirm the format and range of input data before processing, handling errors gracefully to prevent unexpected behavior and improve user experience.

The algorithm for counting even and odd numbers uses constant space, as it only requires two integer variables to store the count of even and odd numbers, regardless of the input size . However, this algorithm has a time complexity of O(n) because it needs to iterate through all n integers in the list . Improvements for time complexity could involve parallel processing or batch processing techniques, although for such a simple operation on small input sizes, additional complexity might not be beneficial.

To modify the algorithm to also retrieve the position of the maximum number, a second variable could be introduced to store the index of the current maximum as it is found. During each comparison, update both the maximum value and the index if a new maximum is found . This maintains O(n) time complexity but provides additional positional information without another full array traversal.

The recursive factorial calculation can encounter performance issues such as stack overflow for large inputs, even though input is limited to 20 in the specification . For higher inputs, the recursive depth increases, leading to inefficient stack usage. These issues can be mitigated by converting the recursive algorithm into an iterative one or using tail recursion optimization, which reduces call stack usage. However, due to constraints in the problem, these optimizations aren't directly applicable.

The Java solution converts negative numbers to positive using Math.abs before calculating the sum of digits . This approach is chosen because the problem constraint requires the sum of digits regardless of sign, effectively treating all digits as positive to simplify processing and yield correct results conforming to the problem's design.

The algorithm for finding the maximum number in an array performs exactly n comparisons, where n is the length of the array . This is optimal because every element must be checked once to ensure it is not the maximum. Sorting the array would generally require O(n log n) time, which is inefficient compared to the O(n) time complexity of the linear scan algorithm used for finding the maximum element.

You might also like