[Go to site: main page, start]

0% found this document useful (0 votes)
5 views5 pages

Java Number and String Algorithms

The document contains various Java code snippets demonstrating algorithms for common programming tasks such as checking for palindromes, generating Fibonacci series, calculating factorials, identifying Armstrong numbers, checking for prime numbers, reversing numbers and strings, checking for anagrams, counting vowels and consonants, removing duplicates from strings, finding the largest and smallest elements in an array, sorting an array, and finding the second largest element. Each code snippet includes the logic and expected output. These examples serve as practical implementations of fundamental programming concepts.
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)
5 views5 pages

Java Number and String Algorithms

The document contains various Java code snippets demonstrating algorithms for common programming tasks such as checking for palindromes, generating Fibonacci series, calculating factorials, identifying Armstrong numbers, checking for prime numbers, reversing numbers and strings, checking for anagrams, counting vowels and consonants, removing duplicates from strings, finding the largest and smallest elements in an array, sorting an array, and finding the second largest element. Each code snippet includes the logic and expected output. These examples serve as practical implementations of fundamental programming concepts.
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

Palindrome Number

int num = 121, rev = 0, temp = num;

while (temp != 0) {

int digit = temp % 10;

rev = rev * 10 + digit;

temp /= 10;

[Link](num == rev ? "Palindrome" : "Not Palindrome");

Output: Palindrome

Fibonacci Series

int n = 10, a = 0, b = 1;

[Link](a + " " + b);

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

int c = a + b;

[Link](" " + c);

a = b;

b = c;

Output: 0 1 1 2 3 5 8 13 21 34

Factorial

int num = 5, fact = 1;

for (int i = 1; i <= num; i++) {

fact *= i;

[Link]("Factorial: " + fact);

Output: Factorial: 120

Armstrong Number

int num = 153, sum = 0, temp = num;

while (temp != 0) {

int digit = temp % 10;

sum += digit * digit * digit;


temp /= 10;

[Link](num == sum ? "Armstrong" : "Not Armstrong");

Output: Armstrong

Prime Number Check

int num = 29, count = 0;

for (int i = 2; i <= num / 2; i++) {

if (num % i == 0) {

count++;

break;

[Link]((count == 0) ? "Prime" : "Not Prime");

Output: Prime

Reverse a Number

int num = 1234, rev = 0;

while (num != 0) {

rev = rev * 10 + num % 10;

num /= 10;

[Link]("Reversed: " + rev);

Output: Reversed: 4321

Reverse a String

String str = "hello", rev = "";

for (int i = [Link]() - 1; i >= 0; i--)

rev += [Link](i);

[Link]("Reversed: " + rev);

Output: Reversed: olleh

Check Anagram

String str1 = "listen", str2 = "silent";


char[] a = [Link]();

char[] b = [Link]();

[Link](a);

[Link](b);

[Link]([Link](a, b) ? "Anagram" : "Not Anagram");

Output: Anagram

Count Vowels and Consonants

String str = "Hello World";

int vowels = 0, consonants = 0;

str = [Link]();

for (char c : [Link]()) {

if (c >= 'a' && c <= 'z') {

if ("aeiou".indexOf(c) != -1)

vowels++;

else

consonants++;

[Link]("Vowels: " + vowels + ", Consonants: " + consonants);

Output: Vowels: 3, Consonants: 7

Remove Duplicates from String

String str = "programming";

String result = "";

for (int i = 0; i < [Link](); i++) {

if (![Link]([Link]([Link](i))))

result += [Link](i);

[Link]("After removing duplicates: " + result);

Output: After removing duplicates: progamin

Find Largest and Smallest Element

int[] arr = {4, 2, 8, 1, 9};


int min = arr[0], max = arr[0];

for (int i = 1; i < [Link]; i++) {

if (arr[i] < min) min = arr[i];

if (arr[i] > max) max = arr[i];

[Link]("Min: " + min + ", Max: " + max);

Output: Min: 1, Max: 9

Sort an Array

int[] arr = {5, 1, 4, 2, 8};

for (int i = 0; i < [Link] - 1; i++) {

for (int j = i+1; j < [Link]; j++) {

if (arr[i] > arr[j]) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

[Link]("Sorted: ");

for (int i : arr) [Link](i + " ");

Output: Sorted: 1 2 4 5 8

Second Largest Element

int[] arr = {5, 1, 9, 6, 2};

int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;

for (int num : arr) {

if (num > first) {

second = first;

first = num;

} else if (num > second && num != first) {

second = num;

}
[Link]("Second Largest: " + second);

Output: Second Largest: 6

Common questions

Powered by AI

The provided sorting algorithm uses a basic selection sort method, comparing each element with all subsequent elements and swapping when needed. This behavior is typical of basic sorting algorithms, prioritizing simplicity over efficiency. Its limitations include a higher time complexity of O(n^2) for large datasets, making it inefficient compared to more advanced algorithms like quicksort or mergesort for substantial arrays .

Two strings are verified as anagrams by sorting their characters and comparing the sorted versions. If the sorted strings are identical, the originals are anagrams. This method works because anagrams must contain the same characters with identical frequencies, and sorting aligns these frequencies in order .

The algorithm determines if a number is a palindrome by reversing the number and checking if it is equal to the original number. It uses a while loop to extract each digit of the original number, building the reversed number digit by digit. If the original and reversed numbers are identical, the number is considered a palindrome .

The algorithm removes duplicates by checking if each character is already present in a result string before adding it. While this method is straightforward, it becomes inefficient as the input string grows because each insertion potentially requires searching through the result string, leading to a time complexity of O(n^2), where n is the string's length. A more efficient approach might use a data structure like a hash set to reduce time complexity .

The algorithm checks if a number is prime by dividing it by all integers up to its half, counting how many divisors exist. If the count remains zero, the number is prime, otherwise, it's not. This method is not the most efficient for large numbers as it checks more numbers than necessary. More efficient algorithms exist, such as testing divisibility only up to the square root or using the Sieve of Eratosthenes for a range of numbers .

Both processes involve reversing the order of elements. For numbers, the digits are extracted from the number, effectively building a new reversed number by multiplying the current result by ten and adding the last digit. For strings, characters are appended to a new string in reverse index order from the original. The operations differ mainly in their handling of data types and the methods of accessing individual components (digits vs characters).

The method initializes two variables to track the smallest and largest values, iterating through the array and updating these variables based on comparisons. This approach is efficient for linear traversal (O(n)), but doesn't sort the array, focusing only on extrema detection. It's suitable when only extrema are needed without altering the original order of elements or requiring additional data processing after sorting .

The logic initializes two variables to track the largest and second-largest elements. It iterates through the array, updating these values based on comparisons. However, this approach might miss multiple maximum values or handle negative numbers improperly. Improvements could involve using a max heap to maintain the largest and second-largest efficiently or sorting the array first for clarity, though at a possible increase in computational cost .

The Fibonacci series is generated using an iterative approach where the first two numbers are initialized to 0 and 1. The loop calculates the next term by adding the last two terms, continuing until 'n' terms are generated. For n=10, the output is: 0 1 1 2 3 5 8 13 21 34 .

The process to verify if a number is an Armstrong number involves calculating the sum of the cubes of its digits and comparing it to the original number. The algorithm extracts each digit using modulo operation, cubes the digit, adds it to a running total, and then checks if this total equals the original number. If they match, the number is an Armstrong number .

You might also like