Skip to content

Instantly share code, notes, and snippets.

@vishr
Created July 20, 2011 01:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vishr/1094137 to your computer and use it in GitHub Desktop.
Save vishr/1094137 to your computer and use it in GitHub Desktop.
Basic Java Programs
import java.util.Arrays;
/**
* @author Vishal Rana
*
*/
public class BasicJavaCode {
// Factorial
public int factorial(int x) {
int f = x == 0 ? 1 : x;
while (x > 1) {
f *= x - 1;
x--;
}
return f;
}
// Factorial using recursion
public int factUsingRecur(int x) {
if (x == 0 || x == 1) {
return 1;
}
return x * factUsingRecur(x - 1);
}
// Reverse a string
public String reverseStr(String str) {
StringBuffer revStr = new StringBuffer();
for (int i = str.length() - 1; i >= 0; i--) {
revStr.append(str.charAt(i));
}
return revStr.toString();
}
// Capitalize
public String capitalize(String str) {
StringBuffer capStr = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (i != 0 && str.charAt(i - 1) == ' ') {
capStr.append(Character.toUpperCase(c));
} else {
capStr.append(c);
}
}
return capStr.toString();
}
// Palindrome
public boolean isPalindrome(String str) {
int len = str.length();
int i = 0;
int j = len - 1;
while (i <= len / 2) {
if (str.charAt(i) != str.charAt(j)) {
return false;
}
i++;
j--;
}
return true;
}
// Anagram
public boolean isAnagram(char[] word1, char[] word2) {
Arrays.sort(word1);
Arrays.sort(word2);
if (String.valueOf(word1).equals(String.valueOf(word2))) {
return true;
}
return false;
}
// LCM
public int calcLCM(int x, int y) {
int max = Math.max(x, y);
int min = Math.min(x, y);
int i = 1;
while (true) {
int z = max * i;
if (z % min == 0) {
return z;
}
i++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment