[Go to site: main page, start]

0% found this document useful (0 votes)
2 views2 pages

Java Basic Optimized

The document presents optimized solutions for basic Java problems, including Fibonacci calculation, prime checking, palindrome verification, number reversal, GCD computation, finding the maximum in an array, and string reversal. Each solution is accompanied by a concise code snippet demonstrating the implementation. The focus is on efficiency, with several algorithms achieving optimal time and space complexities.

Uploaded by

sudharsanrj1971
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)
2 views2 pages

Java Basic Optimized

The document presents optimized solutions for basic Java problems, including Fibonacci calculation, prime checking, palindrome verification, number reversal, GCD computation, finding the maximum in an array, and string reversal. Each solution is accompanied by a concise code snippet demonstrating the implementation. The focus is on efficiency, with several algorithms achieving optimal time and space complexities.

Uploaded by

sudharsanrj1971
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

Java Basic Problems - Optimized Solutions

Fibonacci (Optimized O(n), O(1))


int fib(int n){
if(n<=1) return n;
int prev=0, curr=1;
for(int i=2;i<=n;i++){
int next=prev+curr;
prev=curr;
curr=next;
}
return curr;
}

Prime Check (Optimized)


boolean isPrime(int n){
if(n<=1) return false;
for(int i=2;i*i<=n;i++){
if(n%i==0) return false;
}
return true;
}

Palindrome Number
boolean isPalindrome(int n){
int rev=0, temp=n;
while(n>0){
rev=rev*10 + n%10;
n/=10;
}
return temp==rev;
}

Reverse Number
int reverse(int n){
int rev=0;
while(n>0){
rev=rev*10 + n%10;
n/=10;
}
return rev;
}

GCD (Euclidean Algorithm)


int gcd(int a,int b){
while(b!=0){
int temp=b;
b=a%b;
a=temp;
}
return a;
}
Find Max in Array
int max(int[] arr){
int max=arr[0];
for(int x:arr){
if(x>max) max=x;
}
return max;
}

Reverse String
String reverse(String s){
char[] arr=[Link]();
int l=0,r=[Link]-1;
while(l<r){
char temp=arr[l];
arr[l]=arr[r];
arr[r]=temp;
l++; r--;
}
return new String(arr);
}

You might also like